首页 > 解决方案 > 需要帮助以递归方式遍历 Javascript 对象的所有级别

问题描述

我正在尝试创建一个对象,在这个对象中将是name和下的其他对象的数组children。真的我想从另一个对象创建一个层次结构。

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

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"
            }
          ]
        }
      ]
    }
  ]
}

标签: javascriptreactjsobjectrecursion

解决方案


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;
}

推荐阅读