How to convert an array to an object

I would like to include this:

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

:

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

he assigns the last pair to the object

+4
source share
4 answers

Spread array in Object # assign :

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

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

console.log(myObj);
Run codeHide result

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

+11
source

I would agree with Ori that your question seems to be related to creating an indexed object, which is usually not a good plan, but if your object with numbers is necessary for the key, you can do it like this:

let newObj = {};
myArray.forEach((val, index) => { newObj[index] = val });
+2

Array.reduce(), :

const myArray = [
  { city: "NY", color: 'blue', rodents: { small: false, medium: false, large: true } },
  { status: 'full', color: 'red' },
  { sandwich: 'flavourful' }
]
    
// item is each object in your array
const reduced = myArray.reduce((newObj, item) => {
  // existing props will be overwritten by newer object entries in the array
  // this example is same as Object.assign spread with right to left precedence,
  // until you want more custom logic
  Object.keys(item).forEach((key) => newObj[key] = item[key])
  return newObj
}, {})
    
console.log(reduced)
Hide result
+2
source
let myArray = [ {city: "NY"}, {status: 'full'} ];

let newObj = myArray.reduce((acc, curr) => {
    Object.keys(curr).forEach(val => {
    acc[val] = curr[val]
  })
  return acc
}, {})

console.log(newObj)

This syntax is supported in IE according to caniuse.com

+1
source

Source: https://habr.com/ru/post/1687586/


All Articles