0

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
4
  • 2
    [{...}} and {} are not very descriptive. How do you want to convert the array to an object? If it is only one element why not just arr[0] ? Commented Sep 23, 2021 at 18:22
  • Because of TS complainings for arr[0]. Commented Sep 23, 2021 at 18:25
  • I definitely remember that I can reduce this somehow, but I didn't manage to find a solution Commented Sep 23, 2021 at 18:25
  • What is the TypeScript error/warning about the use of arr[0]? Commented Sep 23, 2021 at 18:27

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

0

Solution was array.reduce((acc, x) => ({...acc,...x}))

answered Sep 23, 2021 at 19:05

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.