1

I want to convert JSON array to a single object. PFB the details

Array:

[{ "item-A": "value-1" }, { "item-B": "value-2" }]

Expected Result:

{ "item-A": "value-1", "item-B": "value-2" }

I have tried following options but result is not what I was expecting

let json = { ...array };

json = Object.assign({}, array);

json = array.reduce((json, value, key) => { json[key] = value; return json; }, {});

Result:

{"0":{"item-A":"value-1"},"1":{"item-B":"value-2"}}
0

2 Answers 2

3

You can use Object.assign and spread the array

const arr=[{ "item-A": "value-1" }, { "item-B": "value-2" }];

console.log(Object.assign({},...arr));

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

Comments

1

You can use reduce like how you did it with more attention like this:

let array = [{ "item-A": "value-1" }, { "item-B": "value-2" }];

let object = array.reduce((prev, curr) => ({ ...prev, ...curr }), {});

console.log(object);

2 Comments

this is printing only second object { 'item-B': 'value-2' }
no way, i already tested it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.