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'}
scriobh
  • 868
  • 10
  • 25
  • `val.subs.id` is undefined because `subs` is an array, you'll need another bit of logic to check the inner array – Sterling Archer Feb 13 '23 at 19:41
  • `const result = cars.find(({id,subs}) => id === selectedId || subs.find(({id})=> id === selectedId))` – Anon Feb 13 '23 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? – scriobh Feb 13 '23 at 19:42
  • i think that works if you put the or on the first find – Anon Feb 13 '23 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. – Solomon Ucko Feb 13 '23 at 19:45
  • `const result = cars.find((val, i) => val.subs[i].id === selectedId || val.id === selectedId)` – Chris G Feb 13 '23 at 19:51
  • check this: https://stackoverflow.com/questions/53938203/javascript-recursive-search-on-an-array-of-objects/75440755#75440755 – 697 Feb 13 '23 at 20:15

0 Answers0