gpt4 book ai didi

javascript - 递归构建对象

转载 作者:行者123 更新时间:2023-12-02 15:31:05 25 4
gpt4 key购买 nike

我有一个类似于以下 obj 的对象。

var obj = [
{ id: 1, name: "animals" },
{ id: 2, name: "animals_cat" },
{ id: 3, name: "animals_dog" },
{ id: 4, name: "animals_weazle" },
{ id: 5, name: "animals_weazle_sand shadow weazle" },
{ id: 11, name: "fruits" },
{ id: 32, name: "fruits_banana" },
{ id: 10, name: "threes" },
{ id: 15, name: "cars" }
];

对象应转换为以下方案:

var items = [
{ id: 11, name: "fruits", items: [
{ id: 32, name: "banana" }
]},
{ id: 10, name: "threes" },
{ id: 1, name: "animals", items: [
{ id: 2, name: "cat" },
{ id: 3, name: "dog" },
{ id: 4, name: "weazle", items: [
{ id: 5, name: "sand shadow weazle" }
]}
]},
{ id: 15, name: "cars" }
];

我尝试了很多,但不幸的是没有成功。我对 obj 执行了 $.each,对其执行了 split('_') 并将其推送到项目。但我怎样才能做到无限深度并将其插入正确的类别呢?

我很高兴获得任何帮助。

最佳答案

也许这有帮助。

它与Array.prototype.forEach一起使用来处理objArray.prototype.reduce来获取正确的分支和 Array.prototype.some 用于插入新对象的右侧数组元素。

此提案适用于排序且一致的数据。

var obj = [
{ id: 1, name: "animals" },
{ id: 2, name: "animals_cat" },
{ id: 3, name: "animals_dog" },
{ id: 4, name: "animals_weazle" },
{ id: 5, name: "animals_weazle_sand shadow weazle" },
{ id: 11, name: "fruits" },
{ id: 32, name: "fruits_banana" },
{ id: 10, name: "threes" },
{ id: 15, name: "cars" }
],
tree = [];

obj.forEach(function (a) {
var path = a.name.split('_'),
o = {};
o.id = a.id;
path.reduce(function (r, b) {
o.name = b;
r.some(function (c) {
if (c.name === b) {
c.items = c.items || [];
r = c.items;
return true;
}
});
return r;
}, tree).push(o);
});

document.write('<pre>' + JSON.stringify(tree, 0, 4) + '</pre>');

更新:项目独立顺序的版本。

var obj = [
{ id: 5, name: "animals_weazle_sand shadow weazle" },
{ id: 32, name: "fruits_banana" },
{ id: 1, name: "animals" },
{ id: 2, name: "animals_cat" },
{ id: 3, name: "animals_dog" },
{ id: 4, name: "animals_weazle" },
{ id: 11, name: "fruits" },
{ id: 10, name: "threes" },
{ id: 15, name: "cars" },
{ id: 999, name: "music_pop_disco_euro"}
],
tree = [];

obj.forEach(function (item) {
var path = item.name.split('_'),
o = tree;

path.forEach(function (a, i) {
var oo = { name: a, items: [] },
last = path.length - 1 === i,
found = o.some(function (b) {
if (b.name === a) {
if (last) {
b.id = item.id;
return true;
}
b.items = b.items || [];
o = b.items;
return true;
}
});
if (!found) {
if (last) {
o.push({ id: item.id, name: a });
} else {
o.push(oo);
o = oo.items;
}
}
});
});

document.write('<pre>' + JSON.stringify(tree, 0, 4) + '</pre>');

关于javascript - 递归构建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33320213/

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