gpt4 book ai didi

javascript - 从对象的javascript数组创建树结构

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

我有一个像这样的对象数组..

var obj_1 = {id:1, title:"Title 1", unitId:0, line: 0};
var obj_2 = {id:2, title:"Title 1.1", unitId:1, line: 0};
var obj_3 = {id:3, title:"Title 1.2", unitId:1, line: 1};
var obj_4 = {id:4, title:"Title 1.1.1", unitId:0, line: 1};
var obj_5 = {id:5, title:"Title 2", unitId:0, line: 1};

var obj_list = [obj_1,obj_2,obj_3,obj_4,obj_5];

我想把json转成树结构,我的结果结构是这样的

Unit 0: {
Line 0: {
children: {
{id:1, title:"Title 1", unitId:0, line: 0}
}
},
Line 1: {
children: {
{id:4, title:"Title 1.1.1", unitId:0, line: 1},
{id:5, title:"Title 2", unitId:0, line: 1}
}
}
}
Unit 1: {
Line 0: {
children: {
{id:2, title:"Title 1.1", unitId:1, line: 0}
}
},
Line 1: {
children: {
{id:2, title:"Title 1.2", unitId:1, line: 2}
}
}
}

如果有人知道怎么做,请回答。提前致谢

最佳答案

您可以采用所需键的数组进行嵌套,并使用这些键构建新对象,并在末尾将对象推送到 children 属性。

var data = [{ id: 1, title: "Title 1", unitId: 0, line: 0 }, { id: 2, title: "Title 1.1", unitId: 1, line: 0 }, { id: 3, title: "Title 1.2", unitId: 1, line: 1 }, { id: 4, title: "Title 1.1.1", unitId: 0, line: 1 }, { id: 5, title: "Title 2", unitId: 0, line: 1 }],
keys = [['unitId', 'Unit'], ['line', 'Line']],
result = data.reduce((r, o) => {
var target = keys.reduce((q, [k, t]) => {
var key = [t, o[k]].join(' ');
return q[key] = q[key] || {};
}, r);
(target.children = target.children || []).push(o);
return r;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

与特殊键的字母相同。

var data = [{ id: 1, title: "Title 1", unitId: 0, line: 0 }, { id: 2, title: "Title 1.1", unitId: 1, line: 0 }, { id: 3, title: "Title 1.2", unitId: 1, line: 1 }, { id: 4, title: "Title 1.1.1", unitId: 0, line: 1 }, { id: 5, title: "Title 2", unitId: 0, line: 1 }],
keys = [['unitId', 'Unit'], ['line', 'Line', v => (10 + v).toString(36).toUpperCase()]],
result = data.reduce((r, o) => {
var target = keys.reduce((q, [k, t, fn = v => v]) => {
var key = [t, fn(o[k])].join(' ');
return q[key] = q[key] || {};
}, r);
(target.children = target.children || []).push(o);
return r;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 从对象的javascript数组创建树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58389410/

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