你能帮我吗 - 我有以下数据列表:
var data = [
{ id:'1', childId: ["2", "3"] },
{ id:"2", childId: ["4"] },
{ id:"3", childId: ["4", "5"] },
{ id:"4", childId: null },
{ id:"5", childId: null }
];
我想获取连接节点 id 的数组
var connections = findConnections('1') //id
id = 1 -->[]
id = 2 -->['1']
id = 3 --> ['1']
id = 4 --> ['3','2']
id = 5 -->['3']
最佳答案
您可以迭代数组和 childId
并将这些值作为具有 id
数组的对象的键。
var data = [{ id: "1", childId: ["2", "3"] }, { id: "2", childId: ["4"] }, { id: "3", childId: ["4", "5"] }, { id: "4", childId: null }, { id: "5", childId: null }],
targets = data.reduce((r, { id, childId }) => {
r[id] = r[id] || [];
(childId || []).forEach(k => (r[k] = r[k] || []).push(id));
return r;
}, {});
console.log(targets);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 递归迭代数组对象并返回连接的 id 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60155464/