1

Input:

const array=[{key: '1', value: 'VALUE1'},{key: '2', value: 'VALUE2'},{key: '1', value: 'VALUE3'},{key: '3', value: 'VALUE4'}]

Expected:

const array=[{key: '1', value: 'VALUE1','VALUE3'},{key: '2', value: 'VALUE2'},{key:'3', value: 'VALUE4'}]
p4avinash
  • 548
  • 2
  • 4
  • 15
  • https://stackoverflow.com/questions/33850412/merge-javascript-objects-in-array-with-same-key – Usama Apr 11 '22 at 05:24

3 Answers3

0

I hope the below function will solve your problem :

var arvConcat = (r) =>{
    var rr=[],or=[];
    for(let ri of r){        
        if(typeof rr[ri.key] === 'undefined')rr[ri.key]=[];
        rr[ri.key].push(ri.value);
    }
    for(let ri in rr){
        or.push({key:ri,value:rr[ri]});
    }
    return or;
}

let r = [{
  key: '1',
  value: 'VALUE1'
}, {
  key: '2',
  value: 'VALUE2'
}, {
  key: '1',
  value: 'VALUE3'
}, {
  key: '3',
  value: 'VALUE4'
}];

let newR = arvConcat(r);

console.log(newR);

Thanks

Pran Paul
  • 68
  • 6
0

You can achieve this using a normal for loop

let array = [{
    key: '1',
    value: 'VALUE1',
  },
  {
    key: '2',
    value: 'VALUE2',
  },
  {
    key: '1',
    value: 'VALUE3',
  },
  {
    key: '3',
    value: 'VALUE4',
  },
];

let i = 0;
while (i < array.length) {
  if (i + 1 <= array.length) {
    for (let x = i + 1; x < array.length; x++) {
      if (array[i].key === array[x].key) {
        array[i].value = `${array[x].value} ${array[i].value}`;
        array.splice(x, 1);
      }
    }
    i++
  }
}
console.log(array);
brk
  • 48,835
  • 10
  • 56
  • 78
0

One way to do it is using Object.values and reduce

//Input:
const array = [{
  key: '1',
  value: 'VALUE1'
}, {
  key: '2',
  value: 'VALUE2'
}, {
  key: '1',
  value: 'VALUE3'
}, {
  key: '3',
  value: 'VALUE4'
}]

const result = Object.values(array.reduce((a,o) => {
      a[o.key] = a[o.key] || {'key': o.key, 'value' : []};
      a[o.key]['value'].push(o.value);
      return a;
    }, {}));

console.log(result);
J_K
  • 688
  • 5
  • 12