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 ?

1

3 Answers 3

2

You can use Array.map. Here it is.

let array=['a','b','c']
const res = array.map(item => ({name: item}))
console.log(res)

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

Comments

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);

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.