为方便起见,我想将一些JSON数据重组为不同的格式。我从服务器获取它的格式对我来说不方便;所有项目都在一个节点中,但其中一些项目有parent: id
,告诉我们该项目的父项。
我想从JsonFromSrver
获取JSON结构并重组为resultJson
。我还需要能够在修改后以原始格式将数据发送回服务器。
var JsonFromSrver = [
{
"id": 1,
"type": "folder",
"title": "HeadItem1",
},
{
"id": 2,
"type": "folder",
"title": "HeadItem2",
},
{
"id": 33,
"parent": 1,
"type": "file",
"title": "ChildItem",
},
{
"id": 103,
"parent": 2,
"type": "file",
"title": "ChildItem"
}
]
var resultJson = [
{
"id": 1,
"type": "folder",
"title": "HeadItem1",
"children":
[{
"id": 33,
"parent": 1,
"type": "file",
"title": "ChildItem"
}]
},
{
"id": 2,
"type": "folder",
"title": "HeadItem2",
"children":
[{
"id": 103,
"parent": 2,
"type": "file",
"title": "ChildItem"
}]
}
]
答案 0 :(得分:1)
我只是将数据收集到分层对象结构中,然后进行字符串化:
var result = {};
for (var j in JsonFromSrver) {
var obj = JsonFromSrver[j];
if (!obj.parent) {
result[obj.id] = obj;
continue;
}
var parentObj = result[obj.parent];
if (!parentObj.children) parentObj.children = [];
parentObj.children.push(obj);
}
resultJson = [];
for (var i in result) {
resultJson.push(result[i]);
}
console.log(JSON.stringify(resultJson));