gpt4 book ai didi

javascript - 使用 Javascript 从嵌套的 JSON 排序索引

转载 作者:行者123 更新时间:2023-11-30 14:17:12 25 4
gpt4 key购买 nike

我怎样才能像这样递归地将排序键添加到无限层次结构中:

[
{
"id": "D41F4D3D-EA9C-4A38-A504-4415086EFFF8",
"name": "A",
"parent_id": null,
"sortNr": 1,
"children": [
{
"id": "07E556EE-F66F-49B5-B5E4-54AFC6A4DD9F",
"name": "A-C",
"parent_id": "D41F4D3D-EA9C-4A38-A504-4415086EFFF8",
"sortNr": 3,
"children": []
},
{
"id": "8C63981E-0D30-4244-94BE-658BAAF40EF3",
"name": "A-A",
"parent_id": "D41F4D3D-EA9C-4A38-A504-4415086EFFF8",
"sortNr": 1,
"children": [
{
"id": "0BA32F23-A2CD-4488-8868-40AD5E0D3F09",
"name": "A-A-A",
"parent_id": "8C63981E-0D30-4244-94BE-658BAAF40EF3",
"sortNr": 1,
"children": []
}
]
},
{
"id": "17A07D6E-462F-4983-B308-7D0F6ADC5328",
"name": "A-B",
"parent_id": "D41F4D3D-EA9C-4A38-A504-4415086EFFF8",
"sortNr": 2,
"children": []
}
]
},
{
"id": "64535599-13F1-474C-98D0-67337562A621",
"name": "B",
"parent_id": null,
"sortNr": 2,
"children": []
},
{
"id": "1CE38295-B933-4457-BBAB-F1B4A4AFC828",
"name": "C",
"parent_id": null,
"sortNr": 3,
"children": [
{
"id": "D1E02274-33AA-476E-BA31-A4E60438C23F",
"name": "C-A",
"parent_id": "1CE38295-B933-4457-BBAB-F1B4A4AFC828",
"sortNr": 1,
"children": [
{
"id": "76A8259C-650D-482B-91CE-D69D379EB759",
"name": "C-A-A",
"parent_id": "D1E02274-33AA-476E-BA31-A4E60438C23F",
"sortNr": 1,
"children": []
}
]
}
]
}
]

我想要一个可排序的索引。例如 0000.0001.00030001.0003 用于节点 A-C。

leadingZeroes 的函数是

function fillZeroes (num) {
var result = ('0000'+num).slice(-4);
if (num===null){
return result
} else {
return '0000';
}
}

它应该在每个层级中按排序编号排序,每次都应该重新设置排序编号,因为我想通过将它设置为 1,5 来进行重新排列以将其插入到 1 和 2 之间(稍后用于拖动和下降能力)。所以 1;1,5;2 应该变成 1;2;3 然后可以像上面那样转换成排序索引。

我还需要它来进行缩进和面包屑导航。

如何为每个对象插入正确的排序索引?

题目主要是递归部分。我对 JavaScript 很陌生

非常感谢

最佳答案

基于@georg 的出色回答。基于 sortNr 对象属性的稍微调整的解决方案。您可以直接运行它,将 json 作为您的对象。排序索引写入 sortOrder 属性。

// Mutates the given object in-place.
// Assigns sortOrder property to each nested object
const indexJson = (json) => {

const obj = {children: json};

const format = (xs) => xs.map(x => pad(x, 4)).join('.');
const pad = (x, w) => (10 ** w + x).toString().slice(-w);

const renumber = (obj, path) => {
obj.path = path;
obj.sortOrder = format(path);
obj.children.slice()
.sort((obj1, obj2) => obj1.sortNr - obj2.sortNr)
.forEach((c, n) => renumber(c, path.concat(n+1)));
};

renumber(obj, []);
};

indexJson(json);

console.log(JSON.stringify(json, null, 2));

关于javascript - 使用 Javascript 从嵌套的 JSON 排序索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53392644/

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