javascript - 需要帮助以递归方式遍历 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"
}
]
}
]
}
]
}
解决方案
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;
}
推荐阅读
- java - 如果我们只删除 1 个元素,我们可以在迭代时删除吗?
- excel - 从 excel 触发的 Chrome 中的下载不起作用
- functional-programming - 在另一个函数 ocaml 中处理递归函数
- php - 无论如何将array_combined插入数据库?
- scala - 在 Play 框架(scala)中与 MySQL 交互的推荐方式?
- javascript - Javascript动画仅在到达网页的某个部分时触发
- javascript - 如何修复内容可编辑 HTML 元素的插入符号
- node.js - 如何在猫鼬中填充具有对象数组的对象?
- python-3.x - 如何从我的数据框中删除方括号?
- mongodb - 如何在 mongodb 的查询中使用?