+ 3
Remove a particular object from an array which is inside an array of objects.
I would like to remove the label: '321' from the items array. I have tried a hard-coded workaround considering my original array would not change. Need suggestions on how to write this in a better way. Not so good with JS. https://code.sololearn.com/c3GT4nT5FVc1/?ref=app
4 Answers
+ 5
Here is my solution, I commented each step if you dont understand something fill free to ask me.
This code can remove every label with this value if this is what you are looking for.
https://code.sololearn.com/cnqt7QmR7l40/?ref=app
+ 5
I think filter is the best attempt here, and reassign it to the actual item in the JSON structure.
If you need to change more elements in multiple places, put it inside a loop.
To print the whole nested structure, you can use JSON.stringify()
arr[1].items = arr[1].items.filter(o => o.label!="321");
console.log(JSON.stringify(arr, null, 2));
+ 3
const out = arr.map(a => {
const {items, ...rest} = a;
const newItems = a.items.filter(i => i.label!== '321');
return {rest, items:newItems}
});
https://code.sololearn.com/cdW6x6r972bP/?ref=app
+ 3
Thank you all for the help, CalviŐ˛ I can see that your solution is somewhat similar to what I did. We have to filter that particular array and assign the new one back to the original one.
Tibor Santa thanks for the JSON.stringify() suggestion and even I thought that using filter would be the best way. I just wanted to know whether the object can be changed in place without creating a new array.