Reputation: 3
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?
Upvotes: 0
Views: 56
Reputation: 4519
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 find
after 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 name
is 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)
Upvotes: 1