4

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}
];
1
  • typo var data = [ {x: 0, value: 1}, {x: 1, value: 2}, {x: 2, value: 3} ]; Commented Aug 31, 2015 at 2:35

3 Answers 3

17

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

var data = values.map(function(el, i) {
   return {
     x: i,
     value: el
   }
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

6 Comments

Do not use for...in on arrays. This is like the model case for that argument.
@Oka Thanks. Didn't knew that. Is the modified code good enough?
I didn't downvote, but your answer has several problems. 1. OP wants to create an array of objects not an object. 2. You shouldn't use the for ... in loop for iterating through arrays. 3. The x and y should be separate properties. Define the _dict as an array, iterate properly and then use the Array.prototype.push method for pushing an object into the array.
@Vohuman Thanks for commenting. You didn't downvote but I did upvote your answer. I am new to javascript as well that's why the answer is mediocre :)
Thanks for that :). Yes, but you forgot to define the _dict variable as an array. var _dict = [];
|

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.