我试图以下列方式重组JSON数组。在输出中,我需要id
作为关键,并将对象本身作为它的值。
示例输入:
[
{
"id": "1",
"children": [
{
"id": "1-1",
"children": [
{
"id": "1-1-1",
"children": []
},
{
"id": "1-1-2",
"children": []
}
]
},
{
"id": "1-2",
"children": []
}
]
},
{
"id": "2",
"children": []
},
{
"id": "3",
"children": [
{
"id": "3-1",
"children": []
}
]
}
]
必需的输出:
{
"1": {
"id": "1",
"children": {
"1-1": {
"id": "1-1",
"children": {
"1-1-1": {
"id": "1-1-1",
"children": []
},
"1-1-2": {
"id": "1-1-2",
"children": []
}
}
},
"1-2": {
"id": "1-2",
"children": []
}
}
},
"2": {
"id": "2",
"children": []
},
"3": {
"id": "3",
"children": {
"3-1": {
"id": "3-1",
"children": []
}
}
}
}
以下代码几乎给出了我所需要的答案。
function restruct(arr) {
var newArray = arr.map(function(obj) {
var t = {};
if (obj.children)
obj.children = restruct(obj.children);
t[obj.id] = obj;
return t;
});
return newArray;
}
输出结果为:
[
{
"1": {
"id": "1",
"children": [
{
"1-1": {
"id": "1-1",
"children": [
{
"1-1-1": {
"id": "1-1-1",
"children": []
}
},
{
"1-1-2": {
"id": "1-1-2",
"children": []
}
}
]
}
},
{
"1-2": {
"id": "1-2",
"children": []
}
}
]
}
},
{
"2": {
"id": "2",
"children": []
}
},
{
"3": {
"id": "3",
"children": [
{
"3-1": {
"id": "3-1",
"children": []
}
}
]
}
}
]
如果您注意到,除children
节点外,一切都按预期输出。当我需要具有键值对的对象时,它返回对象数组。有人可以帮我吗?
答案 0 :(得分:3)
您无法使用map
,因为它会返回一个数组,您可以改为使用forEach
,例如:
function restruct(arr) {
var result = {};
arr.forEach(function(obj) {
if (obj.children) {
obj.children = restruct(obj.children);
}
result[obj.id] = obj;
});
return result;
}
答案 1 :(得分:0)
function restruct(arr) {
var result = {};
arr.forEach(function(obj) {
if (obj.children) {
obj.children = restruct(obj.children);
}
result[obj.id] = obj;
});
return result;
}