-1

Is there a way for me to create an object where the key is the same and the values are set from an array.

I want the key = data and value to be set from an array.

key = data
arr = ['abc', 'pqr', 'xyz']

I need my object to be:

my_obj = [{data: 'abc'}, {data: 'pqr'}, {data: 'xyz'}]

I am not sure how to create such an object.

4
  • No, that wouldn't work. A key must be unique. Given your requirements, why could you not just use my_obj = { data: ['abc', 'pqr', 'xyz'] };? Commented Apr 9, 2020 at 0:43
  • No, JavaScript objects cannot have duplicate keys. The keys must all be unique. stackoverflow.com/questions/3996135/… Commented Apr 9, 2020 at 0:44
  • Does this answer your question? JS associative object with duplicate names Commented Apr 9, 2020 at 0:45
  • I edited my question. I meant an array of objects Commented Apr 9, 2020 at 0:46

1 Answer 1

0

You can achieve that by using map(), something like:

let arr = ['abc', 'pqr', 'xyz']

let my_obj = arr.map(e => ({ data: e }))

console.log(my_obj[0].data) // 'abc'
console.log(my_obj[1].data) // 'pqr'
console.log(my_obj[2].data) // 'xyz

console.log(my_obj)

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

4 Comments

To use the string assigned to the key variable as the key of the object, you can use arr.map(e => ({ [key]: e })). See codeburst.io/…
I'm not sure we want a computed property name in this case, OP seems to want just data.
I saw "I want the key = data..." in the question and thought a computed property name was required.
Got it, I think the OP literally meant the object keys to be "data" :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.