forEach on array of object(s) returning last item

Hi All,

Hope ya’ll having a great day.

How do i fix this forEach() to return all the items in the thingsTodo array? It only returns the last item now. Works perfectly fine with plain arrays but as soon as i put objects in the array it only returns the last item

const thingsTodo = [{task: 'Walk', task: 'Run', task: 'Jog', task: 'Sprint'}];

thingsTodo.forEach((todo) => {
    let p = document.createElement('p');
    p.textContent = todo.task;
    document.querySelector('#divcontainer').appendChild(p);    
});

That is because you have an array with one element (an object) and the object has the same property (task) listed 4 times. It will only retain the last value assigned to the property. You could simply use an array of tasks like:

const thingsTodo = ['Walk', 'Run', 'Jog', 'Sprint'];

thingsTodo.forEach((todo) => {
    let p = document.createElement('p');
    p.textContent = todo;
    document.querySelector('#divcontainer').appendChild(p);    
});

Hi RandellDawson,

Thanks for replying.

Yes, that works great. But i want to have it this way so that new tasks can be added via input field and push them into

thingsTodo.push({task: input.value})

These sould be JSON stringified after input and check if string is found and return JSON.parse(thingsTodo) and add to the array. The reason for this is that i want to add them in localStorage with key and value. But only show the value in the divcontainer. It’s just i’m a bit lost on how to do this exactly.

If you want an array of objects, then create an array of objects.

const thingsTodo = [
  {task: 'Walk'},
  {task: 'Run'},
  {task: 'Jog'},
  {task: 'Sprint'}
];

thingsTodo.forEach((todo) => {
    let p = document.createElement('p');
    p.textContent = todo.task;
    document.querySelector('#divcontainer').appendChild(p);   
});

Keep in mind, you could still store them the original way in local storage and achieve the same results.

1 Like