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'}
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)
using reduce it would be very easy. there you have how it works and a working example.
array = [{
profile: 'pippo'
}, {
profile: 'mickey'
}]
const finalObj = array.reduce((accum, cv, index) => {
accum[index] = cv['profile']
return accum;
}, {})
console.log(finalObj)