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; }
添加回答
舉報