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

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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)

Comments

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)

Comments

0

You can also try

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

OR

Object.assign({}, ...jsonx)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.