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?
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.
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.
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.
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>
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With