1

I have a problem I can't get my head around. If I am looking for an object with a certain ID in a possibly infinite data structure, how can I loop through it until I find the object I need and return that object?

If this is what my data looks like, how can I get the object with id === 3 ?

{
  id: 0,
  categories: [
    {
      id: 1,
      categories: [
        {
          id: 2,
          categories: [ ... ]
        },
        {
          id: 3,
          categories: [ ... ]
        },
        {
          id: 4,
          categories: [ ... ]
        },
      ]
    }
  ]
}

I tried the following:

findCategory = (categoryID, notesCategory) => {
  if (notesCategory.id === categoryID) {
    return notesCategory;
  }
  for (let i = 0; i < notesCategory.categories.length; i += 1) {
    return findCategory(categoryID, notesCategory.categories[i]);
  }

  return null;
};

But that doesn't get ever get to id === 3. It checks the object with id: 2 and then returns null. It never gets to the object with id: 3.

Here is a JSbin: https://jsbin.com/roloqedeya/1/edit?js,console

Eddy Vinck
  • 410
  • 1
  • 4
  • 16

2 Answers2

1

Here is the case. when you go in to the first iteration of 'for' loop, because of the return call, the execution is go out from the function. you can check it by using an console.log to print the current object in the begin of your function.

try this

function find(obj, id) {
    if(obj.id === id) {
        console.log(obj) // just for testing. you can remove this line
        return obj
    } else {
        for(var i = 0; i < obj.categories.length; i++) {
            var res = find(obj.categories[i], id);
            if(res) return res;
        }
   }
}

hope this will help you. thanks

Viran Malaka
  • 417
  • 4
  • 10
  • Thank you so much for your explanation, this solved my problem. I will need to take a good look at this so I can understand why this works. – Eddy Vinck Aug 29 '18 at 16:53
0

You need to store the intermediate result and return only of the object is found.

function findCategory(object, id) {
    var temp;
    if (object.id === id) {
        return object;
    }
    object.categories.some(o => temp = findCategory(o, id));    
    return temp;
}

var data = { id: 0, categories: [{ id: 1, categories: [{ id: 2, categories: [] }, { id: 3, categories: [] }, { id: 4, categories: [] }] }] }
    result = findCategory(data, 3);
  
console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392