4

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'}
Kobe
  • 6,226
  • 1
  • 14
  • 35
Rayden C
  • 139
  • 1
  • 6
  • `array.reduce((o,x,i)=>(o[i]=x.profile,o),{});` – Jared Smith Dec 04 '19 at 14:37
  • 1
    Does this answer your question? [How do I convert array of Objects into one Object in JavaScript?](https://stackoverflow.com/questions/19874555/how-do-i-convert-array-of-objects-into-one-object-in-javascript) – dw_ Dec 04 '19 at 14:39

3 Answers3

4

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)
Kobe
  • 6,226
  • 1
  • 14
  • 35
2

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)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

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)
Prince Hernandez
  • 3,623
  • 1
  • 10
  • 19