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

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.

Answers:

Answer

Try this simple logic

var arr=[{"name1":"value1"},{"name2":"value2"}];
var obj = {}; //create the empty output object
arr.forEach( function(item){ 
   var key = Object.keys(item)[0]; //take the first key from every object in the array
   obj[ key ] = item [ key ];  //assign the key and value to output obj
});
console.log( obj );

Answer

You could run a reduce over the array and return a new object. But it is important to remember that if properties are the same they will be overwritten.

const newObject = array.reduce((current, next) => {
  return { ...current, ...next};
}, {})

If you are using es5 and not es6:

var newObject = array.reduce(function(current, next){
  return Object.assign({}, current, next);
}, {})
Answer

use with Array#forEach and Object.keys

var arr = [{"name1": "value1"},{"name2": "value2"}];
var obj = {};
arr.map(k => Object.keys(k).forEach(a => obj[a] = k[a]))
console.log(obj)

Answer

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);

Answer

Try this:

var arr=[{"name1":"value1"},{"name2":"value2"}];
 var new_arr=[];
 $.each(arr,function(index){
   $.each(arr[index],function(key,value){
    var nw_obj={};
    nw_obj[key]=value;
    new_arr.push(nw_obj);
   });
 });
console.log(JSON.stringify(new_arr));
Answer

Using for...in loop :

var arr=[{"name1":"value1"},{"name2":"value2"}];

var obj = {};
for (var i in arr) {
  obj[Object.keys(arr[i])] = arr[i][Object.keys(arr[i])];
}

console.log(obj);

Using Array.map() method with ES6 :

var arr=[{"name1":"value1"},{"name2":"value2"}];

var obj = {};

arr.map(item => obj[Object.keys(item)] = item[Object.keys(item)]);

console.log(obj);

Using Object.assign() method with ES6 spreaqd(...) assignment :

let arr=[{"name1":"value1"},{"name2":"value2"}];

let obj = Object.assign({}, ...arr);

console.log(obj);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.