Convert an array of an object to a 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 next 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} ]; 
+5
source share
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 result is not JSON, but a regular JavaScript object; if it were JSON, the key names would be in quotation marks. You can, of course, convert your JavaScript object to JSON using JSON.stringify .

+9
source

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); 
+4
source

All Articles