How to convert an array of objects to object with key value pairs
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);
Try this simple logic
var arr=[{"name1":"value1"},{"name2":"value2"}];var obj = {}; //create the empty output objectarr.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 );
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);}, {})