简体   繁体   中英

Vanilla JS. Removing objects from an array within a for each method?

Hope you can help me. I'm trying to find an object in an array based on it's content and then once I've found that object, remove it from the array completely (So that I can then update the local storage with the newly modified array).

let object = JSON.parse(localStorage.items);

// returns the following: 
// [{text: 'Taco'}, {text: 'Pizza'}, {text: 'Curry'}]

object.forEach((obj, i) => {
  obj.text === 'Taco' ? object.splice(i) : console.log(`${i}: ${obj.text} is not a Taco.`);
});

At this point I'd expect the object array to now only contain Pizza and Curry but it still contains Taco for some reason and I am super confused, The forEach method spits out two console logs. one for Pizza and one for Curry but nothing actually happens to the Taco.

Is anyone able to help me understand why this isn't working?

You might find filter easier to use instead:

const notTacos = arr.filter(obj => obj.text !== 'Taco');

You're problem is object.splice(i) when the second parameter (end index) is omitted it is considered as object.length-1 since the Taco found at 0th index so it removes all the elements, Array.splice

 let a = [{text: 'Taco'}, {text: 'Pizza'}, {text: 'Curry'}] let b = [{text: 'Taco'}, {text: 'Pizza'}, {text: 'Curry'}] a.splice(0) b.splice(0,1) console.log(a) console.log(b)

But as a good practice you should never mutate ( deleting the complete element ) the array when you're iterating over it, better use filter

 let object = [{text: 'Taco'}, {text: 'Pizza'}, {text: 'Curry'}] let final = object.filter(({ text }) => text.== 'Taco') console.log(final)

Dont change collection you are iterating over. It still in progress of iteration and you are changing collection itself.

Use Filter method of Natvie js

Const filteredValue = object.filter( obj => obj.text !== 'Taco')

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM