gpt4 book ai didi

javascript - 来自 JSON 的父子关系设置

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:42:34 24 4
gpt4 key购买 nike

我有以下 JSON 数据:

[
{id: 1, indent: '1'},
{id: 2, indent: '1.1'},
{id: 3, indent: '1.2'},
{id: 4, indent: '2'},
{id: 5, indent: '2.1'},
{id: 6, indent: '2.2'},
{id: 7, indent: '2.2.1'},
{id: 8, indent: '1.2.1'},
{id: 9, indent: '3'},
]

我想把它转换成如下所示:

[
{id: 1, indent: '1', parent: null},
{id: 2, indent: '1.1', parent: 1},
{id: 3, indent: '1.2', parent: 1},
{id: 4, indent: '2', parent: null},
{id: 5, indent: '2.1', parent: 4},
{id: 6, indent: '2.2', parent: 4},
{id: 7, indent: '2.2.1', parent: 6},
{id: 8, indent: '1.2.1', parent: 3},
{id: 9, indent: '3', parent: null},
]

我可以使用 2 个 for 循环(外部循环和内部循环)来实现这一点,但我正在寻找一些有效的方法来做到这一点。

ex: 
forloop each node
get indent and check if dots ('.') are more than one
if true
for-loop the array and check for indent that start with the indent and ends with dot + 1

最佳答案

除非您的 json 中有超过 100000 个这些项目(这似乎不太可能,因为下载/发送需要很长时间),否则您的方法就可以正常工作。

您可以做的最佳优化是利用 ID 有序这一事实。由于引用不是,这将要求您在前进时跟踪 id 以缩进对象中的引用。

看起来像这样

var jsonObj = [
{id: 1, indent: '1'},
{id: 2, indent: '1.1'},
{id: 3, indent: '1.2'},
{id: 4, indent: '2'},
{id: 5, indent: '2.1'},
{id: 6, indent: '2.2'},
{id: 7, indent: '2.2.1'},
{id: 8, indent: '1.2.1'},
{id: 9, indent: '3'},
];

var parentIds = {};
for(var i = 0; i < jsonObj.length; i++){
var obj = jsonObj[i];
var dot = obj.indent.lastIndexOf('.');
if(dot > -1){
obj.parent = parentIds[obj.indent.substr(0,dot)];
}else{
obj.parent = null;
}
parentIds[obj.indent] = obj.id;
}

console.log(jsonObj);
document.querySelector("#d").innerHTML = JSON.stringify(jsonObj);
<div id="d"></div>

关于javascript - 来自 JSON 的父子关系设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30603707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com