Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

from array of objects to an object [duplicate]

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'}
like image 248
Rayden C Avatar asked Mar 03 '23 02:03

Rayden C


2 Answers

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)
like image 197
Kobe Avatar answered Mar 07 '23 22:03

Kobe


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)
like image 21
Ori Drori Avatar answered Mar 07 '23 22:03

Ori Drori