需要帮助将递归json对象转换为另一个json对象。
我的输入对象如下所示:
{
person:
{
name: 'John Henry',
age: 63
},
children:
[
{
person:
{
name: 'Paul Henry',
age: 40
},
children:
[
{
person:
{
name: 'Tom Henry',
age: 10
}
}
{
person:
{
name: 'Mike Henry',
age: 12
}
}
]
},
{
person:
{
name: 'Wilson Henry',
age: 30
}
},
{
person:
{
name: 'Richard Henry',
age: 59
}
}
]
}
我想要的输出是:
[{
name: 'John Henry',
attributes: { age: 63 },
children:
[
{
name: 'Paul Henry',
attributes: { age: 40 },
children: [
{
name: 'Tom Henry',
attributes: { age: 10 }
},
{
name: 'Mike Henry',
attributes: { age: 12 }
}
]
},
{
name: 'Wilson Henry',
attributes: { age: 30 }
},
{
name: 'Richard Henry',
attributes: { age: 59 }
}
]
}];
这是我到目前为止所尝试过的,但却被卡在了递归部分。不确定如何把所有东西放在一起。:
var tree = {};
var getFamilyTree = function (input) {
tree.name = input.person.name;
tree.attributes = { 'age': input.person.age };
tree.children = [];
input.children.forEach(function (child) {
//not sure how to recursively go through the child nodes.
});
};
答案 0 :(得分:1)
在函数开头创建一个新的输出对象。
对于每个孩子,再次给孩子打电话getFamilyTree()
- 它将是新的input
。将该调用的结果附加到新子列表中。
返回新创建的对象。
类似的东西:
function getFamilyTree(input)
{
var newb = { 'attributes': {} };
for ( f in input.person ) // we may have attributes other than "age"
if (f == 'name')
newb.name = input.person[f];
else
newb.attributes[f] = input.person[f];
if (input.children && input.children.length)
{
newb.children = [];
for ( var i = 0; i < input.children.length; ++i )
{
newb.children.push(getFamilyTree(input.children[i]));
}
}
return newb;
}
var orig = {
person:
{
name: 'John Henry',
age: 63
},
children:
[
{
person:
{
name: 'Paul Henry',
age: 40
},
children:
[
{
person:
{
name: 'Tom Henry',
age: 10
}
},
{
person:
{
name: 'Mike Henry',
age: 12
}
}
]
},
{
person:
{
name: 'Wilson Henry',
age: 30
}
},
{
person:
{
name: 'Richard Henry',
age: 59
}
}
]
};
function getFamilyTree(o)
{
var newb = { 'attributes': {} };
for ( f in o.person ) // we may have attributes other than "age"
if (f == 'name')
newb.name = o.person[f];
else
newb.attributes[f] = o.person[f];
if (o.children && o.children.length)
{
newb.children = [];
for ( var i = 0; i < o.children.length; ++i )
{
newb.children.push(getFamilyTree(o.children[i]));
}
}
return newb;
}
console.log( JSON.stringify( getFamilyTree(orig), null, " " ) );
&#13;