Home > Net >  convert a simple javascript arary to a list of objects
convert a simple javascript arary to a list of objects

Time:07-01

So i'm trying to do something pretty simple.

I have an array that looks like this

l = [0.5, 4.5, 7.5]

I want to convert it to the following array of objects

obj = [
  {value: 0.5, width:2},
  {value: 4.5, width:2},
  {value: 7.5, width:2}
]

I seem to keep tripping up on this. Any help would be much appreciated. thanks

CodePudding user response:

Something like this?

const numbers = [ 0.5, 4.5, 7.5 ];
const objects = numbers.map( n => ({ value: n, width: 2 });

CodePudding user response:

You want to first make an object with the value field containing the number on the array, and then assign the width in that same object. This can be done with a for loop.

numbers = [0.5, 4.5, 7.5]
obj = []

for (number in numbers) {
   obj.push({value: number, width:2} )
}
  • Related