Nik*_*erg 7 javascript arrays typescript
我有一个对象数组,它们都有一个路径和一个名称属性。喜欢
[
{
"id": "1",
"path": "1",
"name": "root"
},
{
"id": "857",
"path": "1/857",
"name": "Animals"
},
{
"id": "1194",
"path": "1/857/1194",
"name": "Dinasours"
},
...and so on
]
Run Code Online (Sandbox Code Playgroud)
以下是一些路径示例
1/1279/1282
1/1279/1281
1/1279/1280
1/857
1/857/1194
1/857/1194/1277
1/857/1194/1277/1278
Run Code Online (Sandbox Code Playgroud)
我想把它变成一个多维数组,如:
1/1279/1282
1/1279/1281
1/1279/1280
1/857
1/857/1194
1/857/1194/1277
1/857/1194/1277/1278
Run Code Online (Sandbox Code Playgroud)
如您所知,数据量要大得多。
有没有一种巧妙的方法来转换这些数据?
我想知道这是否足以满足您的需求?
我将把这些对象称为节点(只是因为我是一个图论专家,这就是我的工作方式)。
Map
。(纯粹是为了提高效率。从技术上讲,每次需要时,您都可以通过 id 从头开始找到每个节点。)这将导致没有子节点的节点实际上没有children
属性(而不是children
只有一个属性[]
)。我也没有path
从对象中删除/删除该属性。
请注意,如果存在没有相应对象的路径片段,则此操作将不起作用。
const nodes = [
{ id: '1', path: '1', name: 'root' },
{ id: '857', path: '1/857', name: 'Animals' },
{ id: '1194', path: '1/857/1194', name: 'Dinasours' }
//...and so on
];
const index = new Map();
for (let node of nodes) {
index.set(node.id, node)
}
for (let node of nodes) {
const fragments = node.path.split('/');
const parentId = fragments[fragments.length - 2];
const parent = index.get(parentId);
if (parent !== undefined) {
parent.children = parent.children || [];
if (!parent.children.includes(node)) {
parent.children.push(node);
}
}
}
// TODO: Decide which node is the root.
// Here's one way to get the first (possibly only) root.
const root = index.get(nodes[0].path.split('/')[0]);
console.dir(root, { depth: null });
Run Code Online (Sandbox Code Playgroud)