0

I have an tree structured object e.g

var x = [{
  id: 1,
  children: [{
    id: 11,
    children: [],
  }, {
    id: 12,
    children: [{
      id: 121,
      name:'jogn',
      children: []
    }]
  }]
}, {
  id: 2,
  children: [],
}]

And i would like to find object with specific ID in it. I made

function printObj(obj , val) {
  for( var i = 0; i < obj.length ; i++){
         if( obj[i].id == val){
         return obj[i];
         }
         if( obj[i].children.length > 0 ){
            printObj( obj[i].children)
         }
    }
}

function. The problem is when i invoke it

var g = printObj(x , 121);
alert(x.name)

it returns undefined instead of jogn altought when i pop some alert if it findes set value it does find it . Why is it returning wrong object then?

2
  • 2
    What if you alert g.name instead of x? Commented Jul 15, 2016 at 13:57
  • Also, you don't return anything from the printObj(children) so the recursive result will just disappear. Commented Jul 15, 2016 at 13:59

2 Answers 2

3

Two problems with this line:

printObj( obj[i].children);
  1. It's missing its second argument

  2. You need to return its result if it finds one

So

var possibleResult = printObj( obj[i].children, val);
// -------------------------------------------^^^^^
if (possibleResult) {
    return possibleResult;
}

Separately, in your testing, you looked for x.name where you wanted g.name.

Fixed:

var x = [{
  id: 1,
  children: [{
    id: 11,
    children: [],
  }, {
    id: 12,
    children: [{
      id: 121,
      name: 'jogn',
      children: []
    }]
  }]
}, {
  id: 2,
  children: [],
}];

function printObj(obj, val) {
  for (var i = 0; i < obj.length; i++) {
    if (obj[i].id == val) {
      return obj[i];
    }
    if (obj[i].children.length > 0) {
      var possibleResult = printObj(obj[i].children, val);
      if (possibleResult) {
        return possibleResult;
      }

    }
  }
}

var g = printObj(x, 121);
console.log(g.name);

Sign up to request clarification or add additional context in comments.

Comments

0

Ramda is great for object and list work from functional approach - here is your data traversed -

    var x = [{
      id: 1,
      children: [{
        id: 11,
        children: [],
      }, {
        id: 12,
        children: [{
          id: 121,
          name: 'jogn',
          children: []
        }]
      }]
    }, {
      id: 2,
      children: [],
    }]


    const findById = (id, list) => map(o => {
      if(o.id === id) return o
      return findById(id, o.children)
    }, list)

    head(flatten(findById(121, x)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.