Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Array of Object to Regular JavaScript Object

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}
];
like image 215
casillas Avatar asked May 10 '15 04:05

casillas


2 Answers

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.

like image 171
Ethan Brown Avatar answered Oct 03 '22 05:10

Ethan Brown


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);
like image 38
jdphenix Avatar answered Oct 03 '22 03:10

jdphenix