+ 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

7th Jul 2022, 9:33 AM
Avinesh
Avinesh - avatar
4 Réponses
+ 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
7th Jul 2022, 10:36 AM
PanicS
PanicS - avatar
+ 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));
7th Jul 2022, 10:54 AM
Tibor Santa
Tibor Santa - avatar
+ 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
9th Jul 2022, 6:21 AM
Calviղ
Calviղ - avatar
+ 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.
9th Jul 2022, 12:28 PM
Avinesh
Avinesh - avatar