-2

I have this sample of code

a = [ { "apple" : 1 } , { "orange" : 2 } ]

and how would I change this to the following?

a = { "apple" : 1,  "orange": 2 }
TheOneTeam
  • 25,806
  • 45
  • 116
  • 158

2 Answers2

3

You could use Object.assign with spread syntax ... for the objects.

var array = [{ apple: 1 }, { orange: 2 }],
    object = Object.assign({}, ...array);
    
console.log(object);

ES5 with Array#reduce and Object.keys

var array = [{ apple: 1 }, { orange: 2 }],
    object = array.reduce(function (r, o) {
        Object.keys(o).forEach(function (k) {
            r[k] = o[k];
        });
        return r;
    }, {});
    
console.log(object);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Use Object.assign.

var a = [ { "apple" : 1 } , { "orange" : 2 } ]


a = Object.assign({}, ...a);

console.log(a);
Dinesh undefined
  • 5,490
  • 2
  • 19
  • 40