简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM