2 回答

TA貢獻1886條經(jīng)驗 獲得超2個贊
不要在回調(diào)中創(chuàng)建const p局部變量reduce,而是使用完成后可訪問的變量reduce,以便您可以訪問最后分配的對象以添加附加屬性(或多個屬性)。
所以改變:
const p = { path, children: r[path].result };
r.result.push(p);
到:
last = { path, children: r[path].result };
r.result.push(last);
并last在塊的作用域中定義為局部變量for。完成后reduce,您可以使用Object.assign來改變“葉子”對象,添加額外的屬性:
Object.assign(last, rest); // rest is whatever needs to be added.
所以你的代碼可以修改如下:
const result = [];
const level = { result };
for (p of pathObjs) {
let last; // This will be the latest added object
let { path, ...rest } = p; // Extract the path and the other properties
path.split('/').reduce((r, path, i, {length}) => {
if (!r[path]) {
r[path] = { result: [] };
last = { path, children: r[path].result };
r.result.push(last);
}
return r[path];
}, level);
Object.assign(last, rest); // Extend with the extra properties.
}

TA貢獻1757條經(jīng)驗 獲得超7個贊
該解決方案重組了您的原始代碼。主要區(qū)別在于路徑列表是相反的,因此我們從葉節(jié)點而不是根開始。
有一個顯式檢查來查看我們是否位于第一個索引(我們可以假設(shè)它是葉子)?;蛘撸绻敢?,您可以檢查是否result已定義,并依賴它而不是索引。
const pathObjects = [{ id: 1, path: "foo/bar/baz" }];
const result = [];
for (let { id, path } of pathObjects) {
const obj = path
.split("/")
.reverse()
.reduce((result, path, index) => {
const node = {
path,
children: result ? [result] : []
};
if (index === 0) {
node.id = id;
}
return node;
}, null);
result.push(obj);
}
console.log(result);
添加回答
舉報