Leo Ku
Leo Ku

Reputation: 83

How do I convert an array of integers to an array of objects?

I would like to convert and array in this format

var values = [1,2,3]; 

To an array in this format

var data = [ 
  {x: 0, value: 1},
  {x: 1, value: 2},
  {x: 2, value: 3}
];

Upvotes: 4

Views: 4574

Answers (3)

sam
sam

Reputation: 2033

Maybe something like this will do the trick:

var values = [1,2,3];
var _dict = [];

for (var i = 0; i < values.length; i++) {
   _dict.push( {x: i, value: values[i]} );
}

JSFiddle

Upvotes: 1

Quovadisqc
Quovadisqc

Reputation: 81

A basic option would be:

var values = [1,2,3]; 

var newValues = [];
for(var i = 0;i < values.length;i++){
    newValues.push( {x: i, values: values[i]} );
}

Upvotes: 1

Ram
Ram

Reputation: 144689

You could simply use the Array.prototype.map method:

var data = values.map(function(el, i) {
   return {
     x: i,
     value: el
   }
});

Upvotes: 17

Related Questions