1

I am trying to convert this array to object with same custom key

let array=['a','b','c']
 let y=    Object.assign({}, [...array]);

I want resualt like this

[{'name':'a'},{'name':'b'},{'name':'c'}]

how I can do this ?

  • Does this answer your question? [How to map array of values to an array of objects](https://stackoverflow.com/questions/55512028/how-to-map-array-of-values-to-an-array-of-objects) – Ivar Dec 22 '21 at 17:16

3 Answers3

2

You can use Array.map. Here it is.

let array=['a','b','c']
const res = array.map(item => ({name: item}))
console.log(res)
michael
  • 4,053
  • 2
  • 12
  • 31
0

Why haven't you tried a simple for loop yet:

let array=['a','b','c']
let ans = []; //initialize empty array
for(let i = 0; i < array.length; i++){ //iterate over initial array
ans.push({name : array[i]}); //push in desired format 
}
console.log(ans);
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
0

For example. With map() or loops like for... or forEach you can do it.

array=['a','b','c']

let res1 = array.map(a => ({name: a}))
console.log('map()', res1)

// or forEach

let res2 = [];
array.forEach(a => {
  res2.push( {name: a})
})

console.log('forEach()', res2)
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79