0

I have the following array:

const result = [{ "1": { status: "ok" }, "2": { status: "ok" } }, { "3": { status: "error" } }]

And I want to convert it to a linear map, like this:

{ "1": { status: "ok" }, "2": { status: "ok" }, "3": { status: "error" } }

In an efficient way.

Currently I was doing

let tickets = {};
result.forEach(e => {
  tickets = { ...tickets, ...e }
});

which supposes re-creating the map multiple times, with the spread syntax.

Any ideas to achieve the same behavior with a lower cost?

Raul
  • 2,673
  • 1
  • 15
  • 52
  • Based on your question... `result` is an `array` with a single object, and your expected result is a single object. So you can do `const expectedResult = result[0]`. And you get what you want. – Pipe Mar 24 '21 at 16:33
  • @Pipe there are 2 objects – Raul Mar 24 '21 at 16:35
  • @Pipe `result` has two objects... look between "2" and "3". @Raul - what do you mean by _lower cost_? Is what you are doing not performant enough? You could use `.reduce` instead of `.forEach` – chazsolo Mar 24 '21 at 16:35
  • 4
    `Object.assign({}, ....result)` – VLAZ Mar 24 '21 at 16:36
  • @Raul My bad, didn't notice that. Thank you. then VLAZ comment is the correct answer – Pipe Mar 24 '21 at 16:38
  • 1
    See [this answer](https://stackoverflow.com/a/63060553/) – VLAZ Mar 24 '21 at 16:42

0 Answers0