Array looks so:
var arr =
[{name: '1112B',
subname:
[
{name: 'sub_1112B'},
{name: 'sub_1112BA'}
]
},
{name: '2112B',
subname:
[
{name: 'sub_2112B'},
{name: 'sub_2112BA'}
]
}];
After executing following code:
arr.map(it => it.subname).find(i => i.name == 'sub_2112BA') i got undefined but it is supposed to be '2112B'.
What am I doing wrong?
2 Answers 2
arr.map(it => it.subname) will create nested array of subname and using .find() will return undefined since it iterate through a nested array, you could use .flat() and then use findafter but it won't return the object containing the subname since you are iterating in the subname array, so instead you can filter the objects of the array and use find on each subname array to check if the desired nameis there
arr =
[{name: '1112B',
subname:
[
{name: 'sub_1112B'},
{name: 'sub_1112BA'}
]
},
{name: '2112B',
subname:
[
{name: 'sub_2112B'},
{name: 'sub_2112BA'}
]
}];
res=arr.filter(x=>(x.subname.find(y=>y.name=="sub_2112B")))
console.log(res)
2 Comments
Array.prototype.filter returns an array and also it will loop through the entire array. if you're really interested in first occurrence, can go with x.find(d => !!d.subname.find(i => i.name == 'sub_2112BA'))Use type-safe equal === in find()
sub2112BAdoesn't exists in your data.