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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Thanks a lot jdphenix, your answer is also correct, I have upvoted. Since Ethan answered first, I marked his answer.

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.