B
B
beefront172018-03-27 18:19:46
JavaScript
beefront17, 2018-03-27 18:19:46

How to turn an array into an object, js?

Good afternoon! Can you please tell me how to turn an array into an object?
Why doesn't this code work?

const toObj = (arr) => {
  let obj = {};
  return arr.forEach((e) => {
   obj = { ...e };
  });
};

An array like this
const arr = [
{test: []}
{test2: []}
...
]

need this
const arr = {
test: []
test2: []
...
}

Why doesn't the spread operator work?
Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene, 2018-03-27
@beefront17

The fact is that in each iteration inside forEach you overwrite the obj object completely (and not expand / supplement it), so that in the last iteration in the obj object there will be only those properties / values ​​\u200b\u200bthat the last element of the array had. Better this way:

const toObj = (arr) => arr.reduce((a, b) => ({ ...a, ...b }));

S
SinGlEBW, 2020-04-21
@SinGlEBW

Here I will leave few people to account. Through reduce it is difficult to understand.

const arr = [
    { test: [1] },
    { test2: [2] },
  ];
let obj = {};
arr.forEach((el) => {
    Object.assign(obj,el);
});

console.dir(obj);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question