-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.

nb_nb_nb
  • 1,243
  • 11
  • 36
  • 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'] };`? – fubar Apr 09 '20 at 00:43
  • No, JavaScript objects cannot have duplicate keys. The keys must all be unique. https://stackoverflow.com/questions/3996135/js-associative-object-with-duplicate-names – Twisty Apr 09 '20 at 00:44
  • Does this answer your question? [JS associative object with duplicate names](https://stackoverflow.com/questions/3996135/js-associative-object-with-duplicate-names) – Twisty Apr 09 '20 at 00:45
  • I edited my question. I meant an array of objects – nb_nb_nb Apr 09 '20 at 00:46

1 Answers1

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)
Luís Ramalho
  • 10,018
  • 4
  • 52
  • 67