Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform an array to an object [duplicate]

I would like to turn this:

let myArray = [ {city: "NY"}, {status: 'full'} ];

to this:

let myObj = { city: "NY", status: 'full' };

while I tried this:

let newObj = {};
for (var i = 0; i < myArray.length; i++) {
  (function(x) {
    newObj = Object.assign(myArray[i]);
  })(i);
}

it assigns the last pair to the object

like image 232
Hamed Mamdoohi Avatar asked Dec 02 '22 12:12

Hamed Mamdoohi


1 Answers

Spread the array into Object#assign:

const myArray = [ {city: "NY"}, {status: 'full'} ];

const myObj = Object.assign({}, ...myArray);

console.log(myObj);

Note: Assign into an empty object. If you omit the empty object, the 1st element of the original array will be mutated (everything will be merged into it).

like image 110
Ori Drori Avatar answered Dec 06 '22 12:12

Ori Drori