ENG1959
ENG1959

Reputation: 3

Find an element in an array of objects

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

Answers (2)

Sven.hig
Sven.hig

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 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)

Upvotes: 1

genius42
genius42

Reputation: 243

Use type-safe equal === in find()

Upvotes: 0

Related Questions