返回对象或对象及其父对象

时间:2016-07-18 15:06:30

标签: javascript object

我的对象有树状结构,例如

var x = [{
  id: '1',
  name: 'one',
  children: [{
    id: '11',
    name: 'oneone',
    children: [{
      id: '111',
      name: 'oneoneone',
    }]
  }]
}]

有更多图层

使用功能

function findObj(obj, val) {
  console.log(obj, val);
  for (var i = 0; i < obj.length; i++) {
    if (obj[i].id == val) {
      return obj[i];
    }
    if (obj[i].hasOwnProperty('children') && obj[i].children.length > 0) {
      var possibleResult = findObj(obj[i].children, val);
      if (possibleResult) {
        return {
          child: possibleResult,
          parent: obj[i]
        }
      }

    }
  }
}

如果它是数组x中的主索引,我缩进返回对象, 或结构if是否在某种层中。 e.g

console.log( findObj(x ,1 ))

返回

Object {id: "1", name: "one", children: Array[1]}

using console.log( findObj( x , 11 ));

返回

{
  child : {
    Object {id: "11", name: "oneone", children: Array[1]} 
  }
  parent : {
    Object {id: "1", name: "one", children: Array[1]}
  }
}

在下一层中,例如

console.log( findObj( x , 111 ))

它返回

{
    child:{
          child:{},
          parent:{}
     }
    parent:{
           child:{}.
           parent:{},
    }
 }

等等。我希望它只返回第一种和第二种情况的返回类型。有什么办法可以实现吗?我想弄清楚但却无法找到解决方案。

Demo

由于 Demo看起来很好的代码最终返回了错误的结果

2 个答案:

答案 0 :(得分:1)

你应该试试这个:

function findObj(obj, val) {
    for (var i = 0; i < obj.length; i++) {
        if (obj[i].id == val) {
            return obj[i];
        }
        if (obj[i].hasOwnProperty('children') && obj[i].children.length > 0) {
            var possibleResult = findObj(obj[i].children, val);
            if (possibleResult) {
                if (possibleResult.child) { //Check if possibleResult has child property, than possibleResut is your result.
                    return possibleResult;
                } else {
                    return {
                        child: possibleResult,
                        parent: obj[i]
                    }
                }
            }
        }
    }
}

您可以查看此更新 DEMO

答案 1 :(得分:1)

您可以使用实际父级的参数扩展您的函数。

function findObj(array, value, parent) {
    var result;
    array.some(function (a) {
        if (a.id === value) {
            result = parent ? [{ child: a, parent: parent }] : a;
            return true;
        }
        if (Array.isArray(a.children)) {
            return result = findObj(a.children, value, a);
        }
    });
    return result;
}

var x = [{ id: '1', name: 'one', children: [{ id: '11', name: 'oneone', children: [{ id: '111', name: 'oneoneone', }] }] }];

console.log(findObj(x, '1'));
console.log(findObj(x, '11'));
console.log(findObj(x, '111'));

相关问题