I have an array with a single element that looks like this [{...}]
All I have to do simply to convert this to an object like this {}
asked Sep 23, 2021 at 18:20
kkkkkkkkkkkkkkkkk
7822 gold badges7 silver badges27 bronze badges
2 Answers 2
I think the answer you are looking for is something like this:
const arr = [
{name: 'name', value: 1},
{name: 'name2', value: 2},
{name: 'name3', value: 3},
{name: 'name4', value: 4},
{name: 'name5', value: 5},
]
const arrToObj = arr.reduce((obj, el) => {
obj[el.name] = el.value
return obj
}, {})
console.log(arrToObj)
answered Sep 23, 2021 at 18:29
Sinan Yaman
5,9562 gold badges21 silver badges40 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Solution was array.reduce((acc, x) => ({...acc,...x}))
answered Sep 23, 2021 at 19:05
kkkkkkkkkkkkkkkkk
7822 gold badges7 silver badges27 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-js
[{...}}and{}are not very descriptive. How do you want to convert the array to an object? If it is only one element why not justarr[0]?arr[0].reducethis somehow, but I didn't manage to find a solutionarr[0]?