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"}}
Dawood Ahmed
  • 1,734
  • 4
  • 23
  • 36

2 Answers2

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));
gorak
  • 5,233
  • 1
  • 7
  • 19
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);
Louay Al-osh
  • 3,177
  • 15
  • 28