5

I have the following array objects

var stats = [
    [0, 200,400], [100, 300,900],[220, 400,1000],[300, 500,1500],[400, 800,1700],[600, 1200,1800],[800, 1600,3000]
];

I would like to know how to convert it to the following JavaScript object.

var stats = [
    {x:0, y:200,k:400}, {x:100, y:300,k:900},{x:220, y:400,k:1000},{x:300, y:500,k:1500},{x:400, y:800,k:1700},{x:600, y:1200,k:1800},{x:800, y:1600,k:3000}
];
casillas
  • 16,351
  • 19
  • 115
  • 215
  • Note that [JSON is a text format, not the same as a JavaScrpt object](http://stackoverflow.com/questions/8294088/javascript-object-vs-json). – Qantas 94 Heavy May 10 '15 at 04:45

2 Answers2

9

Array.prototype.map is what you need:

stats = stats.map(function(x) {
    return { x: x[0], y: x[1], k: x[2] };
});

What you describe as the desired output is not JSON, but a regular JavaScript object; if it were JSON, the key names would be in quotes. You can, of course, convert a JavaScript object to JSON with JSON.stringify.

Ethan Brown
  • 26,892
  • 4
  • 80
  • 92
4

You can use map()

var stats = [
    [0, 200,400], [100, 300,900],[220, 400,1000],[300, 500,1500],[400, 800,1700],[600, 1200,1800],[800, 1600,3000]
];

stats = stats.map(function(el) {
  return {
    x: el[0],
    y: el[1], 
    k: el[2]
  };
}); 

console.log(stats);
jdphenix
  • 15,022
  • 3
  • 41
  • 74
  • Thanks a lot jdphenix, your answer is also correct, I have upvoted. Since Ethan answered first, I marked his answer. – casillas May 10 '15 at 04:44