I have an array like this:
array = [{profile: 'pippo'}, {profile: 'mickey'}]
and I would like to transform it to this:
object = {0: 'pippo', 1: 'mickey'}
You can use a short reduce
:
const array = [{profile: 'pippo'}, {profile: 'mickey'}]
const output = array.reduce((a, o, i) => (a[i] = o.profile, a), {})
console.log(output)
Or even use Object.assign
:
const array = [{profile: 'pippo'}, {profile: 'mickey'}]
const output = Object.assign({}, array.map(o => o.profile))
console.log(output)
However, your output is in the same format as an array, so you could just use map
and access the elements by index (it really just depends on the use case):
const array = [{profile: 'pippo'}, {profile: 'mickey'}]
const output = array.map(o => o.profile)
console.log(output)
Extract the profiles value with Array.map()
and spread into an object:
const array = [{profile: 'pippo'}, {profile: 'mickey'}]
const result = { ...array.map(o => o.profile) }
console.log(result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With