1

I have an array of objects like this

const jsonx =[{"name":"John Doe"},{"name2":"Marry Doe"},{"name3":"Michael"}]

What I am trying to achieve are the values of each object out of the array as follows

{"name":"John Doe","name2":"Marry Doe","name3":"Michael"}

I have tried the following methods, but did not manage to get what I need.

//console.log(Array.of(...jsonx));
//console.log(JSON.stringify(jsonx));
Phesto Mwakyusa
  • 155
  • 1
  • 13

5 Answers5

3

Alternatively, you can make use of ES6's spread syntax and Object.assign. (My favourite way of doing things)

const jsonx =[{"name":"John Doe"},{"name2":"Marry Doe"},{"name3":"Michael"}];
const res = Object.assign({}, ...jsonx);
console.log(res);
wentjun
  • 40,384
  • 10
  • 95
  • 107
1

You can try with Array.prototype.reduce()

The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value.

and Object.assign()

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

const jsonx =[{"name":"John Doe"},{"name2":"Marry Doe"},{"name3":"Michael"}];

var res = jsonx.reduce((a, c) => Object.assign(a, c), {});

console.log(res);
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

You can use reduce for it:

const jsonx =[{"name":"John Doe"},{"name2":"Marry Doe"},{"name3":"Michael"}]
    
    const res = jsonx.reduce((acc,curr) => ({...acc, ...curr}), {});
    
    console.log(res)
ttulka
  • 10,309
  • 7
  • 41
  • 52
0

You can use flatMap() and reduce()

const jsonx =[{"name":"John Doe"},{"name2":"Marry Doe"},{"name3":"Michael"}]

let res = jsonx.flatMap(x => Object.entries(x)).reduce((ac,[k,v]) => ({...ac,[k]:v}),{})
console.log(res)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

You can also try

jsonx.reduce((r, a) => Object.assign(r, a))

OR

Object.assign({}, ...jsonx)
Asim Khan
  • 1,969
  • 12
  • 21