gpt4 book ai didi

javascript - 在给定父 ID 和子项的情况下,在 lodash 中嵌套父子关系

转载 作者:行者123 更新时间:2023-11-30 10:00:45 28 4
gpt4 key购买 nike

如果父项及其子项作为属性给出,我将如何嵌套 json 对象。

数据看起来像:

   "1": {
"id": 1,
"name": "foo",
"parent": null,
"root": 1,
"children": [2, 4, 6],
"posts":[
{ "id": "1", "name": "item1" },
{ "id": "2", "name": "item2" },
{ "id": "3", "name": "item3" }
]
},
"2": {
"id": 2,
"name": "bar",
"parent": 1,
"root": 1,
"children": null,
"posts":[
{ "id": "4", "name": "item4" }
]
},
"3": {
"id": 3,
"name": "bazz",
"parent": null,
"root": 3,
"children": [5, 7],
"posts":[
{ "id": "5", "name": "item5" },
{ "id": "6", "name": "item6" }
]
},
....

使用 lodash 的简单 groupby 不会这样做。

var group = _.groupBy(data, 'parent');

这是一个 fiddle :

http://jsfiddle.net/tzugzo8a/1/

问题的上下文是一个带有子类别的嵌套类别,类别中可以有类别和帖子。

基本上我不想为子项和帖子设置不同的属性,因为它们都是父项的子项。

期望的输出

    "1": {
"id": 1,
"name": "foo",
"parent": null,
"root": 1,
"isCategory": true,
"children": [
{
"id": 2,
"name": "bar",
"parent": 1,
"root": 1,
"isCategory": true,
"children": null
},
{ "id": "1", "name": "item1", isCategory: false },
{ "id": "2", "name": "item2", isCategory: false },
{ "id": "3", "name": "item3", isCategory: false }

]
...
}

最佳答案

这是我对这个问题的看法(fiddle):

var data = getData();

var group = getTree(data);

console.log(group);

function getTree(flat) {
return _.reduce(flat, function (treeObj, item, prop, flatTree) {
var children = _.map(item.children, function (childId) {
return _.set(flatTree[childId], 'isCategory', true);
}).concat(_.map(item.items, function(item) {
return _.set(item, 'isCategory', false);
}));

item.children = !!children.length ? children : null;

delete item.items;

item.parent === null && (treeObj[prop] = item);

return treeObj;
}, {});
}

关于javascript - 在给定父 ID 和子项的情况下,在 lodash 中嵌套父子关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31832934/

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