4

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

Hamed Mamdoohi
  • 131
  • 1
  • 6

4 Answers4

11

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

Ori Drori
  • 183,571
  • 29
  • 224
  • 209
3

You could also use Array.reduce() which will give you more fine grain control:

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)
// you will see `red` overwrite `blue`

EDIT: after examining this answer after a year, I note that it isn't optimized at all for ability to deep clone or deep merge. I recommend studying those aspects closer and to be careful of copying or breaking references if you are working immutably.

There is no issue with this in the above example because all values are primitives.

agm1984
  • 15,500
  • 6
  • 89
  • 113
2

I would tend to agree with Ori that your question seems to be about creating an indexed object which isn't usually a good plan, but if its necessary to key your object with numbers you can do it like this:

let newObj = {};
myArray.forEach((val, index) => { newObj[index] = val });
D Lowther
  • 1,609
  • 1
  • 9
  • 16
1
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

  • A blob of code without any context is not the best answer. Please consider expanding upon this. It is also unclear, even from the context of the question, what "IE Supported" means. –  Oct 16 '17 at 20:55
  • `map` without using the result is a bad pattern for just iterating the array. you could use `forEach`. – Nina Scholz Oct 16 '17 at 21:03