3 回答
TA贡献1799条经验 获得超8个赞
我倾向于避免使用,reduce因为我发现很难阅读其中的代码reduce。所以,这里有一个non-reduce方法。
const data = [
{
parentsList: [
"Assets",
"Icons"
],
},
{
parentsList: [
"Assets",
"Fonts"
],
},
{
parentsList: [
"Programming",
"JavaScript",
"Docs"
],
},
{
parentsList: [
"Programming",
"JavaScript",
"React",
"Libraries",
],
},
];
const processedData = [];
for (const item of data) {
const parents = [...item.parentsList].reverse();
let children = processedData;
const ids = [];
while (parents.length > 0) {
const parent = parents.pop();
ids.push(parent.toLowerCase());
let foundParent = false;
for (const child of children) {
if (child.name === parent) {
children = child.children;
foundParent = true;
break;
}
}
if (!foundParent) {
const newChild = {name: parent, id: ids.join("/"), children: [],};
children.push(newChild);
children = newChild.children;
}
}
}
console.log(processedData);
TA贡献1898条经验 获得超8个赞
forEach您可以将其作为和 的组合来执行此操作reduce,并基于parentsList数组创建嵌套层次结构。
const data = [{"parentsList":["Assets","Icons"]},{"parentsList":["Assets","Fonts"]},{"parentsList":["Programming","JavaScript","Docs"]},{"parentsList":["Programming","JavaScript","React","Libraries"]}]
const result = []
data.forEach(function({ parentsList, ...rest }) {
let id = '';
parentsList.reduce((r, name, i) => {
id += (id.length ? '/' : '') + name.toLowerCase();
if (!r[name]) {
const value = { id, name }
r[name] = {result: []}
if (i != parentsList.length - 1) {
value.children = r[name].result
} else {
Object.assign(value, rest)
}
r.result.push(value)
}
return r[name]
}, this)
}, {result})
console.log(result)
TA贡献1834条经验 获得超8个赞
使用嵌套对象作为哈希表的简短方法。
const
data = [{ parentsList: ["Assets", "Icons"] }, { parentsList: ["Assets", "Fonts"] }, { parentsList: ["Programming", "JavaScript", "Docs"] }, { parentsList: ["Programming", "JavaScript", "React", "Libraries"] }],
tree = data.reduce((t, { parentsList }) => {
parentsList.reduce((r, name, i, a) => {
const id = a.slice(0, i + 1).join('/').toLowerCase();
if (!r[name]) {
r[name] = { _: { name, id } };
(r._.children ??= []).push(r[name]._);
}
return r[name];
}, t);
return t;
}, { _: {} })._.children;
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
添加回答
举报