我們必須列印具有所有直接和間接子級的頂級父級。可以有多個頂級父級。但是每個孩子將只有 1 個頂級父母。輸入和輸出格式如下。輸出應該是一個物件陣列,其中每個物件都應該有一個 id 和一個包含所有子物件的串列。-1 表示頂級父級,子級可能存在也可能不存在(例如:下面輸入中的 6)。
輸入:
[
{
id: 1,
children: [2, 3],
parent: -1,
},
{
id: 2,
children: [4, 5],
parent: 1,
},
{
id: 3,
children: [],
parent: 1,
},
{
id: 4,
children: [],
parent: 2,
},
{
id: 5,
children: [6],
parent: 2,
},
{
id: 7,
children: [8, 9],
parent: -1,
},
{
id: 8,
children: [],
parent: 7,
},
{
id: 9,
children: [],
parent: 7,
},
];
輸出:
[
{
id: 1,
children: [2, 3, 4, 5, 6],
},
{
id: 7,
children: [8, 9],
},
];
我嘗試的解決方案:
function formatData(data) {
const map = {};
for (let datum of data) {
let parentId = datum.parent === -1 ? datum.id : datum.parent;
if (parentId in map) {
map[parentId].push(datum.id, ...datum.children);
} else {
map[parentId] = [];
map[parentId].push(...datum.children);
}
}
}
uj5u.com熱心網友回復:
每個專案都有-1(要使用的根)的父項或已經迭代過的父項的 ID。使用它來迭代專案并為每個根元素找到的每個子 ID 創建一個集合。由于某些物件沒有parent所需的匹配根 ID,因此在第一次迭代時將每個物件的 ID 與其父根快取起來,以便以后出現的物件可以輕松查找。
const data=[{id:1,children:[2,3],parent:-1},{id:2,children:[4,5],parent:1},{id:3,children:[4,5],parent:1},{id:4,children:[],parent:2},{id:5,children:[6],parent:2},{id:7,children:[8,9],parent:-1},{id:8,children:[],parent:7},{id:9,children:[],parent:7}];
function formatData(data) {
const rootParentsById = {};
const outputById = {};
for (const obj of data) {
if (obj.parent === -1) {
outputById[obj.id] = new Set(obj.children);
} else {
const parentId = rootParentsById[obj.parent] ?? obj.parent;
rootParentsById[obj.id] = parentId;
outputById[parentId].add(obj.id);
for (const child of obj.children) {
outputById[parentId].add(child);
}
}
}
return Object.entries(outputById).map(
([id, childrenIdSet]) => ({
id,
children: [...childrenIdSet]
})
);
}
console.log(formatData(data));
uj5u.com熱心網友回復:
這對我有用:
const input = [
{
id: 1,
children: [2, 3],
parent: -1,
},
{
id: 2,
children: [4, 5],
parent: 1,
},
{
id: 3,
children: [],
parent: 1,
},
{
id: 4,
children: [],
parent: 2,
},
{
id: 5,
children: [6],
parent: 2,
},
{
id: 7,
children: [8, 9],
parent: -1,
},
{
id: 8,
children: [],
parent: 7,
},
{
id: 9,
children: [],
parent: 7,
},
];
function formatData(data) {
const tmpTree = [...data];
tmpTree.forEach((d) => {
if (d.parent === -1) return;
const parent = tmpTree.find((p) => p.id === d.parent);
if (parent.childNodes) {
parent.childNodes.push(d);
} else {
parent.childNodes = [d];
}
});
const tree = tmpTree.filter((d) => d.parent === -1);
function getChildren(node) {
const children = [...node.children];
if (node.parent !== -1) {
children.push(node.id);
}
if (node.childNodes) {
children.push(...node.childNodes.flatMap(getChildren));
}
return [...new Set(children)];
}
const final = tree.map((node) => {
const children = getChildren(node);
return {
id: node.id,
children,
};
});
return final;
}
console.log(formatData(input));
它確實會改變輸入中的專案,但您可以根據需要對其進行返工以避免這種情況。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/537856.html
