节点JS-通过键未知对象的键合并对象

时间:2019-05-23 13:47:31

标签: javascript arrays node.js

我有一堆我从Mongo数据库中获取的数据。 简而言之,我的数据看起来像这样:

var a = [{
  "F1": [
    "value1"
  ]
}];

var b = [{
  "8002": [
    "value3",
    "value4"
  ]
}];

var c = [{
    "F1": [
      "value1",
      "value3"
    ]
  },
  {
    '8002': [
      "value5"
    ]
  }
];

a = a.concat(b).concat(c);
console.log(a);

当我将它们结合在一起时,我得到:

[
  { 'F1': ['value1'] },
  { '8002': ['value3', 'value4'] },
  { 'F1': ['value1', 'value3'] },
  { '8002': ['value5'] }
]

但是我需要的是:

[ 
   { 'F1': [ 'value1','value3' ] },
   { '8002': [ 'value3', 'value4','value5' ] }
]

唯一键的值合并的位置。 Node / JavaScript是如何实现的?

2 个答案:

答案 0 :(得分:3)

您可以减少给定的数组,并检查结果集中是否存在相同的键,然后检查值是否存在,然后将值推入结果集中。

var a = [{ F1: ["value1"] }],
    b = [{ 8002: ["value3", "value4"] }],
    c = [{ F1: ["value1", "value3"] }, { 8002: ["value5"] }],
    result = [...a, ...b, ...c].reduce((r, o) => {
        var key = Object.keys(o)[0],
            temp = r.find(p => key in p);

        if (!temp) return r.concat(o);
        o[key].forEach(v => {
            if (!temp[key].includes(v)) temp[key].push(v);
        });
        return r;
    }, []);

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

带有集合的地图。

var a = [{ F1: ["value1"] }],
    b = [{ 8002: ["value3", "value4"] }],
    c = [{ F1: ["value1", "value3"] }, { 8002: ["value5"] }],
    result = Array.from(
        [...a, ...b, ...c].reduce((m, o) => {
            var [k, v] = Object.entries(o)[0];
            return m.set(k, new Set([...(m.get(k) || []), ...v]));
        }, new Map),
        ([k, v]) => ({ [k]: [...v] })
    );

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

答案 1 :(得分:2)

您可以使用reduce()

var a =[ { "F1" : [ "value1" ] } ]; 
var b =[ { "8002" : [ "value3", "value4" ] } ]; 
var c =[ { "F1" : [ "value1", "value3" ] }, { '8002': [ "value5" ] } ];
    
let arr = [...a,...b,...c];

let res = arr.reduce((ac,a) => {
  let key = Object.keys(a)[0];
  ac[key] = (ac[key] || []).concat(a[key]);
  return ac;
})

res = Object.entries(res).map(([k,v]) => ({[k]:v}))

console.log(res)