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'}

2

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.