Pavan
Pavan

Reputation: 1015

Convert Js Array to JSON object with keys

I want to use the same object for jQplot and a library built on jQtable. jQplot is fine with arrays but jQtable's library needs an named object (dictionary).

vals = 
[
 [1, 2],
 [3,5.12],
 [5,13.1],
 [7,33.6],
 [9,85.9],
 [12,54],
[11,219.9]
];

This is my js array I want it to be like

 {
 data: [{
 X: 1,
 Y: 2
 },
 {
 X: 3,
 Y: 5.12
 },
 {
 X: 5,
 Y: 13.1
}]
}

How to convert js array into named JSON array of objects? Are there any built in methods or I define my own method to read up that array and create a String for JSON?

Upvotes: 0

Views: 137

Answers (2)

Samuli Hakoniemi
Samuli Hakoniemi

Reputation: 19049

var array = vals.map(function(val) {
  return {
    X : val[0],
    Y : val[1]
  };
});

Upvotes: 6

kaz
kaz

Reputation: 1190

var data = Object.keys(vals).map(function(key) {
    return {X : vals[key][0], Y : vals[key][1]};
});

Upvotes: 0

Related Questions