Home > Blockchain >  Change array of elements to objects with static key value
Change array of elements to objects with static key value

Time:09-02

So, I have an array as follows.

Array.from(Array(3).keys())
//=> [0, 1, 2]

I wanted to convert this array to object and assign a static key called value to each elements.

So the final result should be

result = [
{
value: 0,
},
 {
value: 1,
},
{
value: 2,
}
]

CodePudding user response:

This is my solution

console.log(Array.from(Array(3).keys()).map(x => ({value: x})))

CodePudding user response:

Any time you need to modify an array, the map method is usually the thing to use. It will essentially loop through the array and return a new value based on what you choose to return.

For this, we are just assigning a static key for each value.

console.log(Array.from(Array(3).keys()).map(v => ({value: v})))

CodePudding user response:

Just map it:

const source = Array.from(Array(3).keys());
const result = source.map(x => ({value: x}));

console.log(result);

CodePudding user response:

For each number, you should append {value: number} to an array. Since this process is made for each number and we want an array as result, we can use map.

Array.from(Array(3).keys()).map(value => {return {value: value}})
  • Related