javascriptarraysjsontypescriptarray-reduce

Aggregate array of object to single distinct value of object javascript


I want to aggregate array of object into single object with each object having distinct value. But My code is not giving me desired output. Can someone please help me?

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), {})

Solution

  • Here I use some helpers from lodash to solve your problem.

    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>