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}
];
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
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With