递归遍历数组对象并返回连接的ID数组

时间:2020-02-10 17:30:40

标签: javascript arrays

能帮我吗-我有以下数据列表:

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']

2 个答案:

答案 0 :(得分:1)

您可以迭代数组和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; }

答案 1 :(得分:0)

谢谢你,关于这种情况呢?

var data = [
  { id: '1', type: 'bananas', yellow: ['2', '3'] },
  { id: '2', type: 'pears', greens: ['4'] },
  { id: '3', type: 'pears', greens: ['4', '5'] },
  { id: '4', type: 'pears', greens: null },
  { id: '5', type: 'pears', greens: null },
];

const MAP_CHILD_ID = {
  bananas: 'yellow',
  pears: 'greens',
};

function getConnections(id) {
  return data.reduce((acc, item) => {
    if (item.childId && item.childId.includes(id)) {
      acc.push(item.id)
    }
    return acc
  }, [])
};

var a = getConnections('1');

想要接收与此ID嵌套的所有ID的数组 s的结果将是['2','3','4','5']