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 ?
CodePudding user response:
You can use Array.map. Here it is.
let array=['a','b','c']
const res = array.map(item => ({name: item}))
console.log(res)
CodePudding user response:
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);
CodePudding user response:
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)