【问题标题】:Recursively iterate over arrays objects and return array of connected ids递归迭代数组对象并返回连接的 id 数组
【发布时间】:2020-02-10 17:30:40
【问题描述】:

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

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

【问题讨论】:

  • 请查看stackoverflow.com/help/how-to-ask 如果您需要帮助,您首先需要向我们展示您尝试过/尝试过的内容以及您在使用该方法时遇到的具体问题

标签: javascript arrays


【解决方案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; }

【讨论】:

    【解决方案2】:

    谢谢你,这个案子怎么样:

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

    【讨论】:

    • 请不要在回答中提出其他问题。相反,请打开一个新问题,或者如果它是一个小修改,请编辑您的问题。
    猜你喜欢
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多