合并具有相同键值对的对象数组内的值

时间:2018-03-15 16:31:08

标签: javascript arrays object lodash

我有以下数组:

     const arr = [  
   {  
      id:"aaa",
      name:"aaa",
      type:"director",
      nodes:[  
         {  
            type:"manager",
            id:"111",
            name:"111"
         }
      ]
   },
   {  
      id:"aaa",
      name:"bbb",
      type:"director",
      nodes:[  
         {  
            type:"manager",
            id:"222",
            name:"222"
         }
      ]
   },
   {  
      id:"aaa",
      name:"aaa",
      type:"director",
      nodes:[  
         {  
            type:"manager",
            id:"333",
            name:"333"
         }
      ]
   },
   {  
      id:"aaa",
      name:"bbb",
      type:"director",
      nodes:[  
         {  
            type:"manager",
            id:"444",
            name:"444"
         }
      ]
   }
]

期望的输出:

        const arr = [  
   {  
      id:"aaa",
      name:"aaa",
      type:"director",
      nodes:[  
         {  
            type:"manager",
            id:"111",
            name:"111"
         },
         {  
            type:"manager",
            id:"333",
            name:"333"
         }
      ]
   },
   {  
      id:"aaa",
      name:"bbb",
      type:"director",
      nodes:[  
         {  
            type:"manager",
            id:"222",
            name:"222"
         },
         {  
            type:"manager",
            id:"444",
            name:"444"
         }
      ]
   }

我正在尝试将上面数组中具有相同键值(id,name和type)对的节点对象数组的值合并到所需的输出中。

我尝试过以下但是arr.reduce徒劳无功,但徒劳无功:

arr.reduce((acc, el) => {
      var existEl = acc.find(e => e.nodes.id === el.nodes.id);
      if (existEl) {   
        existEl = el;
      } else {
        acc.push(el);
      }

      return acc;
    }, []);

非常感谢任何帮助。提前谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用Map并收集具有相同idname

的所有项目

var array = [{ id: "aaa", name: "aaa", type: "director", nodes: [{ type: "manager", id: "111", name: "111" }] }, { id: "aaa", name: "bbb", type: "director", nodes: [{ type: "manager", id: "222", name: "222" }] }, { id: "aaa", name: "aaa", type: "director", nodes: [{ type: "manager", id: "333", name: "333" }] }, { id: "aaa", name: "bbb", type: "director", nodes: [{ type: "manager", id: "444", name: "444" }] }],
    result = [...array.reduce((m, o) => {
        var key = ['id', 'name'].map(k => o[k]).join('|');
        if (m.has(key)) {
            m.get(key).nodes.push(...o.nodes);
        } else {
            m.set(key, Object.assign({}, o, { nodes: o.nodes }));
        }
        return m;
    }, new Map).values()];

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }