Home > Net >  How to combine an array of object within same array and same keys using reduce
How to combine an array of object within same array and same keys using reduce

Time:12-07

I am trying to combine objects inside an array using reduce my object looks like bellow and has the fallowing structure.

[
    {
        "AREA": [
            "EMAC"
        ],
        "SUPER_REGION": [
            "South East Europe Region",
            "East Europe Region",
        ],
    },
    {
        "AREA": [
            "CCA"
        ],
        "SUPER_REGION": [
            "Taiwan",
            "China Hong Kong"
        ],
    }
    
]

Expected output :

{
        "AREA": [
            "EMAC","CCA"
        ],
        "SUPER_REGION": [
            "South East Europe Region",
            "East Europe Region",
            "Taiwan",
            "China Hong Kong"
        ],
}

My current code using reduce :

let sum = finalval.reduce(function (accumulator, { AREA, SUPER_REGION }) {
    accumulator["AREA"]  = AREA;
    return accumulator;
  }, {});

the above code returns me output by combining the values into one string but I want them to be split and added into a single object like shown in expected output. How can i actually push values into these object like we do on arrays using push method ?

CodePudding user response:

You would need to append elements not only to AREA, but to SUPER_REGION as well - to add elements to an array, use .push, not =. But that wouldn't be very general. A more flexible approach would construct the output object by first mapping one of the input objects, with empty arrays as values - then for each input object, iterate over each subarray and push to the key in the output object.

const input = [
    {
        "AREA": [
            "EMAC"
        ],
        "SUPER_REGION": [
            "South East Europe Region",
            "East Europe Region",
        ],
    },
    {
        "AREA": [
            "CCA"
        ],
        "SUPER_REGION": [
            "Taiwan",
            "China Hong Kong"
        ],
    }  
];

const output = Object.fromEntries(
  Object.keys(input[0]).map(key => [key, []])
);
for (const obj of input) {
  for (const [key, subarr] of Object.entries(obj)) {
    output[key].push(...subarr);
  }
}
console.log(output);

.reduce isn't really appropriate here, assuming you want to keep the input unmutated. If you have to use .reduce, it will look a bit confusing for no good reason.

const input = [{
    "AREA": [
      "EMAC"
    ],
    "SUPER_REGION": [
      "South East Europe Region",
      "East Europe Region",
    ],
  },
  {
    "AREA": [
      "CCA"
    ],
    "SUPER_REGION": [
      "Taiwan",
      "China Hong Kong"
    ],
  }
];

const output = input.reduce((a, obj) => {
  for (const [key, subarr] of Object.entries(obj)) {
    a[key].push(...subarr);
  }
  return a;
}, Object.fromEntries(Object.keys(input[0]).map(key => [key, []])));
console.log(output);

CodePudding user response:

const d = [{"AREA":["EMAC"],"SUPER_REGION":["South East Europe Region","East Europe Region"]},{"AREA":["CCA"],"SUPER_REGION":["Taiwan","China Hong Kong"]}]

const r = d.reduce((a,c)=>(Object.keys(c).forEach(k=>a[k].push(...c[k])),a))

console.log(r)

CodePudding user response:

You can achieve this requirement by using Array.reduce() method.

Live Demo :

const arr = [
  {
    "AREA": [
      "EMAC"
    ],
    "SUPER_REGION": [
      "South East Europe Region",
      "East Europe Region",
    ],
  },
  {
    "AREA": [
      "CCA"
    ],
    "SUPER_REGION": [
      "Taiwan",
      "China Hong Kong"
    ],
  }
];

const res = arr.reduce((obj, curr) => {
    Object.keys(curr).forEach(key => {
    obj[key] = obj[key] ? [...obj[key], ...curr[key]] : curr[key]
  })
  return obj
}, {});

console.log(res);

CodePudding user response:

You could merge the arrays from all the objects in the input.

Something along the lines of the code below:

let finalVal = [{
    "AREA": [
      "EMAC"
    ],
    "SUPER_REGION": [
      "South East Europe Region",
      "East Europe Region",
    ],
  },
  {
    "AREA": [
      "CCA"
    ],
    "SUPER_REGION": [
      "Taiwan",
      "China Hong Kong"
    ],
  }
];


function collecItems(prev, curr) {
  // to make it more generic, get the keys from the first element in the array:
  let objectKeys = Object.keys(finalVal[0]);
  console.log(objectKeys);

  // build the object with the keys
  let rtnObj = {};

  objectKeys.forEach(key => {
    // add the values for each key
    rtnObj[key] = [...prev[key], ...curr[key]];
  });
  return rtnObj;
}

let sum = finalVal.reduce(collecItems);

console.log(sum);

  • Related