需要帮助递归迭代Javascript对象的所有级别

问题描述 投票:-1回答:2

我正在尝试创建一个对象,在这个对象中将是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"
            }
          ]
        }
      ]
    }
  ]
}
javascript reactjs object recursion
2个回答
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;
}

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.