0

I have a similar array in the below format. I need to be able to find the object based on the id and it has to search for all the nested arrays (parent and child). And, the selectedId could be also be from the id of parent array.

Could anyone please advise?

Excerpt from my code

const cars = [{
  id: 1,
  name: 'toyota',
  subs: [{
    id: 43,
    name: 'supra'
  }, {
    id: 44,
    name: 'prius'
  }]
}, {
  id: 2,
  name: 'Jeep',
  subs: [{
    id: 30,
    name: 'wranger'
  }, {
    id: 31,
    name: 'sahara'
  }]
}]
const selectedId = 31;
const result = cars.find((val) => val.subs.id === selectedId)
console.log(result)

My expected output should be

{id: 31, name: 'sahara'}
7
  • val.subs.id is undefined because subs is an array, you'll need another bit of logic to check the inner array Commented Feb 13, 2023 at 19:41
  • const result = cars.find(({id,subs}) => id === selectedId || subs.find(({id})=> id === selectedId)) Commented Feb 13, 2023 at 19:41
  • @Anon but that checks only for subs id right? I can just add an or condition inside find for checking for parent ids too? Commented Feb 13, 2023 at 19:42
  • i think that works if you put the or on the first find Commented Feb 13, 2023 at 19:44
  • I'd recommend writing your own for-of loop in this situation, since the existing array methods don't really work for this. Commented Feb 13, 2023 at 19:45

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.