Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an array of objects to object with key value pairs

Tags:

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.

like image 466
HiddenMarkow Avatar asked Apr 26 '17 05:04

HiddenMarkow


People also ask

How do you convert an array of objects into an object object?

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.

How do you convert an object to a key value pair?

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.

Can array have key-value pairs?

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.


1 Answers

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);
like image 199
Nina Scholz Avatar answered Sep 20 '22 06:09

Nina Scholz