Home > Enterprise >  Combine values from an array of objects on the basis of key name
Combine values from an array of objects on the basis of key name

Time:05-06

const input = [{car: 'BMW' }, {car: 'Benz'}, {bike: 'KTM'}, {bike: 'Honda'}]

const output = {car: ['BMW','Benz'], bike: ['KTM','Honda']}

Is this possible?

CodePudding user response:

It's pretty simple - Loop over the array of objects, check if the key exists in output object if not - create key with value - array and push the value else just push the value to existing key.

const input = [{car: 'BMW' }, {car: 'Benz'}, {bike: 'KTM'}, {bike: 'Honda'}]
let output = {};
for(let i = 0 ; i < input.length ; i  ){
    const key = Object.keys(input[i])[0];
    if(!output[key]){
        output[key] = [input[i][key]];
    }else{
        output[key].push(input[i][key])
    }
}

CodePudding user response:

group by problems can be solved using reduce. Here I assumed that each element in the input array has only 1 key value pair

const input = [{car: 'BMW' }, {car: 'Benz'}, {bike: 'KTM'}, {bike: 'Honda'}]

const output = input.reduce((acc,curr)=>{
      const [k,v] = Object.entries(curr)[0]
      acc[k] = acc[k] || []
      acc[k].push(v)
      return acc
},{})

console.log(output)

  • Related