Answer the question
In order to leave comments, you need to log in
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 };
});
};
const arr = [
{test: []}
{test2: []}
...
]
const arr = {
test: []
test2: []
...
}
Answer the question
In order to leave comments, you need to log in
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 }));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question