-3

I have one array of object.

Objs[0] = {Name : "ABC"};
Objs[1] = {Roll : 123}

I want to merge both, It will be like

Objs {
   Name : "ABC",
   Roll : 123
}

Any way to I achieve this?

Angel Politis
  • 10,955
  • 14
  • 48
  • 66
David
  • 4,266
  • 8
  • 34
  • 69
  • Possible duplicate of [Merge multiple objects inside the same array into one object](http://stackoverflow.com/questions/27538349/merge-multiple-objects-inside-the-same-array-into-one-object) – Ramon-san Feb 06 '17 at 07:47
  • http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically you need each in array, n object merge. – Qh0stM4N Feb 06 '17 at 07:58

2 Answers2

4

You can use Object.assign method.

var Objs = [{
  Name: "ABC"
}, {
  Roll: 123
}];

console.log(
  Object.assign.apply(null, [{}].concat(Objs))
)

Or you can use spread syntax instead of Function#apply method.

var Objs = [{
  Name: "ABC"
}, {
  Roll: 123
}];

console.log(
  Object.assign({}, ...Objs)
)
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • @David : use polyfill : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill – Pranav C Balan Feb 07 '17 at 13:58
3

You can try below code.

var jsonObj = {};

$.each(Objs, function(index) {

    $.each(Objs[index], function(key, value) {
        jsonObj[key] = value;

    });
});
Ramon-san
  • 1,007
  • 13
  • 25
Ramu Agrawal
  • 518
  • 6
  • 9