I want to convert an array of objects to object with key value pairs in javascript.
var arr=[{"name1":"value1"},{"name2":"value2"},...}];
How can i convert it to an object such as
{"name1":"value1","name2":"value2",...}
I want it to be supported in majority of browsers.
The quickest way to convert an array of objects to a single object with all key-value pairs is by using the Object. assign() method along with spread operator syntax ( ... ). The Object.
To convert a JavaScript object into a key-value object array, we can use the Object. entries method to return an array with of key-value pair arrays of a given object. Then we can use the JavaScript array map method to map the key-value pair arrays into objects.
Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well. Simple Array eg. We see above that we can loop a numerical array using the jQuery.
You could use Object.assign
and a spread syntax ...
for creating a single object with the given array with objects.
var array = [{ name1: "value1" }, { name2: "value2" }], object = Object.assign({}, ...array); console.log(object);
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