需要帮助递归遍历Javascript对象的所有级别

时间:2019-03-28 01:10:25

标签: javascript reactjs object recursion

我正在尝试创建一个对象,该对象内将是namechildren下的其他对象的数组。我真的想从另一个对象创建层次结构。

我试图创建一个递归函数,但最终得到的是垂直切片而不是整个图片。我不确定如何调整我的递归以回溯添加迭代其他水平对象。

buildHierarchy(json) {
  console.log("Entered Build Hierarchy");

  let newObject;
  newObject = this.buildChildren(json);

  console.log(newObject);
  return newObject

}
buildChildren(json) {
  let returnObject;
  for (var key in json) {
    returnObject = {
      name: key,
      children: []
    };
    var subObject = json[key];

    if (Array.isArray(subObject)) {
      returnObject = {
        name: key,
        _proficiency: subObject
      }
    } else {
      returnObject["children"].push(this.buildChildren(subObject))

    }
  }
  return returnObject;
}

想象一下您在下面有这个json文件

{users: 
  {sandy: {
    posts: [
      { title: 'Bar', comments: [ 'Ok' ] },
    ]
    followers: [
      { name: 'Foo' },
    ]
  }
 ron: {
    photos: [
      { title: 'Foo', comments: [ 'Ok' ] },
    ]
  }
 }
}

我正在寻找类似的东西...

{
  name: "users",
  children: [
    {
      name: "sandy",
      children: [
        {
          name: "posts",
          children: [
            {
              name: "Bar",
              comments: "OK"
            }],
        { name: "followers"
          children: [
            {
              name: "Foo"
            }
          ]
        } 
      }
    ]
  },
    {
      name: "ron",
      photos: [
        {
          name: "photos",
          children: [
            {
              name: "Foo",
              comments: "OK"
            }
          ]
        }
      ]
    }
  ]
}

2 个答案:

答案 0 :(得分:0)

从我看到的输出中,我得出了这些推论:

  • 如果子对象是数组,则将其盲目复制到children
  • 如果子元素是一个对象,则将它们更改为{name: <KEY>, children: <VALUE>}
function buildChildren(json) {
  let returnObject = [];
    if (typeof json !== 'object') {
    return json;
  }
  for (var key in json) {
    if (Array.isArray(json)) {
      returnObject.push(buildChildren(json[key]));
    } else {
      returnObject.push({
        name: key,
        children: buildChildren(json[key])
      });
    }
  }
  return returnObject;
}

答案 1 :(得分:0)

function buildHierarchy(json) {
    console.log("Entered Build Hierarchy");
    let newObject;
    newObject = buildChildren(json);
    console.log(newObject);


}

function buildChildren(json) {
    if (Array.isArray(json)) {
        return {
            _proficiency: json
        }
    }

    var children = Object.keys(json);
    let final = [];
    for (var i = 0; count = children.length, i < count; i++) {
        let result = {
            name: children[i]
        }
        let d = buildChildren(json[children[i]]);
        if (d._proficiency) {
            result._proficiency = d._proficiency;
        } else {
            result.children = d;
        }
        final.push(result);
    }
    return final;
}