将对象数组聚合为对象的单个不同值 javascript

Aggregate array of object to single distinct value of object javascript

我想将对象数组聚合成单个对象,每个对象都有不同的值。但是我的代码没有给我想要的输出。有人可以帮我吗?

My Input : 
    [{
        "obj1" : "value1",
        "obj2" : ["abc", "def"],
        "obj3" : ["ghi"],
        "obj4" : "value4",
    },
    {
        "obj1" : "value2",
        "obj2" : ["abc", "mno"],
        "obj3" : ["klm"],
        "obj4" : "value4",
    }]


Output I want:
{
    "obj1" : ["value1","value2"]
    "obj2" : ["abc", "def","mno"],
    "obj3" : ["ghi","klm"],
    "obj4" : ["value4"]
}

My Code:
const result = filterData.reduce((a,c) => 
  (Object.keys(c).map(k => a[k] = [...a[k] || [], c[k]]), a), {})

这里我使用lodash的一些助手来解决你的问题。

const input = [{
        "obj1" : "value1",
        "obj2" : ["abc", "def"],
        "obj3" : ["ghi"],
        "obj4" : "value4",
    },
    {
        "obj1" : "value2",
        "obj2" : ["abc", "mno"],
        "obj3" : ["klm"],
        "obj4" : "value4",
    }]
    
function customizer(objValue, srcValue) {
  if (_.isArray(objValue)) {
    return _.union(objValue, srcValue);
  }
}
    
const output = input.reduce((acc, cur) => {
  const modifiedCur = _.mapValues(cur, function(o) { return typeof o === 'string' ? [o]: o; }); 
  acc = _.mergeWith(acc, modifiedCur, customizer);
  return acc
},{})    
    
console.log(output)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

您可以使用 array#reduce 从对象数组创建单个对象。您可以使用 Set.

获得不同的值

const data = [{ "obj1" : "value1", "obj2" : ["abc", "def"], "obj3" : ["ghi"], "obj4" : "value4", }, { "obj1" : "value2", "obj2" : ["abc", "mno"], "obj3" : ["klm"], "obj4" : "value4", }],
      result = data.reduce((r,o) => {
        Object.keys(o).forEach(k => {
          r[k] = [...new Set((r[k] || []).concat(o[k]))];
        });
        return r;
      },{});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }