I have an array like so:
const array = [
{
'12345': [
{
name: 'item one',
numbers: ['12345', '77484'],
},
{
name: 'item two',
numbers: ['12345', '65456'],
},
{
name: 'item three',
numbers: ['12345', '33920'],
},
{
name: 'item four',
numbers: ['12345', '99393'],
},
],
},
{
'67890': [
{
name: 'item one b',
numbers: ['67890', '33232'],
},
{
name: 'item two b',
numbers: ['67890', '33456'],
},
{
name: 'item three b',
numbers: ['67890', '77665'],
},
{
name: 'item four b',
numbers: ['67890', '11234'],
},
],
},
]
console.log(array);
If I am given a name as a dynamic variable, for example, 'item three b', how can find that name inside the array of objects of the array of objects to delete it?
I'm stumped when trying to get into the nested array.
Thanks!
1 Answer 1
You can achieve this using forEach loop , then using findIndex and finally splice the data from the array.
const array = [
{
'12345': [
{
name: 'item one',
numbers: ['12345', '77484'],
},
{
name: 'item two',
numbers: ['12345', '65456'],
},
{
name: 'item three',
numbers: ['12345', '33920'],
},
{
name: 'item four',
numbers: ['12345', '99393'],
},
],
},
{
'67890': [
{
name: 'item one b',
numbers: ['67890', '33232'],
},
{
name: 'item two b',
numbers: ['67890', '33456'],
},
{
name: 'item three b',
numbers: ['67890', '77665'],
},
{
name: 'item four b',
numbers: ['67890', '11234'],
},
],
},
]
array.forEach(obj => {
Object.values(obj).forEach(ob => {
var index = ob.findIndex(o => o.name==='item three b');
if(index>-1){
ob.splice(index,1);
}
})
})
console.log(array);
answered Jul 28, 2020 at 17:45
Harmandeep Singh Kalsi
3,3652 gold badges17 silver badges31 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Sememoir
This worked like an absolute charm! Thank you so much!
lang-js
mapoffind, you could get the object. What are you then wanting to do with it? Delete it? That makes it a bit different.item three b, how do I find it in the nested array and delete it. Thanks. I've triedfind()but I cannot get into the nested array withfind(). I can loop through the first level of objects, but I am stumped when getting into the nested array.