Javascript 重新构造JSON数组
我正试图按照以下方式重新构造JSON数组。在输出中,我需要Javascript 重新构造JSON数组,javascript,json,Javascript,Json,我正试图按照以下方式重新构造JSON数组。在输出中,我需要id作为键,对象本身作为它的值 样本输入: [ { "id": "1", "children": [ { "id": "1-1", "children": [ { "id": "1-1-1",
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": []
}
}
]
}
}
]
如果您注意到,除了
子节点
节点外,所有内容都符合预期输出。它返回对象数组,而我需要具有键值对的对象。有人能帮我吗?你不能使用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;
}
好奇使用当前结构有什么错误或问题?似乎对代码更友好me@charlietfl,我使用的JavaScript库需要上述格式作为输入。
function restruct(arr) {
var result = {};
arr.forEach(function(obj) {
if (obj.children) {
obj.children = restruct(obj.children);
}
result[obj.id] = obj;
});
return result;
}