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
  • 145
  • 1
  • 12

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
  • 35,261
  • 9
  • 79
  • 93
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
  • 62,450
  • 9
  • 45
  • 52
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
  • 8,535
  • 4
  • 36
  • 45
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
  • 34,163
  • 5
  • 36
  • 62
0

You can also try

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

OR

Object.assign({}, ...jsonx)
Asim Khan
  • 1,899
  • 11
  • 21