Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge object in IE 11

I have the following array of object:

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

I'm trying to make it as the following:

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

I attempted to make it with the following code:

var Objs = [{   Name: "ABC" }, {   Roll: 123 }];  console.log(   Object.assign.apply(null, [{}].concat(Objs)) // 1 ) or   console.log(   Object.assign({}, ...Objs) // 2 ) 

The problem is that this is not working in IE 11.

I get the errors:

Error for 1 : Unable to get property 'on' of undefined or null reference

Error for 2 : Object doesn't support property or method 'assign'

Any suggestions on how I should merge the object in IE 11?

like image 250
David Avatar asked Feb 07 '17 13:02

David


People also ask

How do I combine multiple objects into one?

To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ... ) Use the Object. assign() method.

Does spread operator work on ie11?

As you said, it doesn´t work in IE, and that is because it´s part of ES6 and that is not (and never will) supported in IE 11. One option to solve it is using transpilers like Babel.

How do I merge objects in ES6?

The easiest way to merge two objects in JavaScript is with the ES6 spread syntax / operator ( ... ). All you have to do is insert one object into another object along with the spread syntax and any object you use the spread syntax on will be merged into the parent object.


2 Answers

You can use jQuery method $.extend() which work in IE 11.

var object = {name: 'John', surname: 'Rowland'};  var newObject = $.extend({}, object);    newObject.age = '30';    console.log(object);  console.log(newObject)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 126
Nebojsa Sapic Avatar answered Sep 30 '22 17:09

Nebojsa Sapic


IE11 does not support Object.assign.

You could iterate the array and the keys and take the values as new property of the result object.

var objs = [{ Name: "ABC" }, { Roll: 123 }],      result =  objs.reduce(function (r, o) {          Object.keys(o).forEach(function (k) {              r[k] = o[k];          });          return r;      }, {});    console.log(result);
like image 24
Nina Scholz Avatar answered Sep 30 '22 18:09

Nina Scholz