我正在使用下面的代码来创建对象(如下):
var data3 = [];
data3.push('{"headers":["Dimension 1","Metric 1","Metric 2"],"rows":[');
for (var i in results.data)
{
object = '["'+ results.data[i].Country +'",'+ results.data[i].Price +','+ results.data[i].Discount+'],';
data3.push(object);
}
data3.push(']}');
我要返回的是以下对象:
var json_data= {"headers":["Dimension 1","Metric 1","Metric 2"],"rows":[["Australia",174,23],["Canada",502,17],["France",242,37],["Germany",102,42],["United Kingdom",126,44],["United States",1246,47],["Australia",680,80],["Canada",1241,66],["Canada",1241,66],["France",150,30],["Germany",244,22],["United Kingdom",501,9],["United States",4960,41],["Australia",9,8],["Canada",3655,70],["France",1654,95],["Germany",1190,36],["United Kingdom",1222,38],["United States",7941,53],["Australia",6829,56],["Canada",1664,75],["France",2995,88],["Germany",1487,100],["United Kingdom",9245,29],["United States",9008,66],["Australia",9376,7],["Canada",1531,31],["France",5421,22],["Germany",6975,41],["United Kingdom",4320,100],["United States",3200,41],["Australia",6688,41],["Canada",699,42],["France",5403,70],["Germany",6377,49],["United Kingdom",2471,14],["United States",6650,4],["Australia",865,70],["Canada",511,20],["France",981,36],["Germany",57,10],["United Kingdom",675,38],["United States",40,72],["Australia",400,63],["Canada",971,90],["France",357,93],["Germany",820,40],["United Kingdom",520,32],["United States",448,24],["Australia",513,40],["Canada",977,8],["France",118,84],["Germany",161,29],["United Kingdom",239,89],["United States",327,79]]};
如何创建对象而不必转换为字符串?
答案 0 :(得分:2)
从results.data
开始,您可以重新排列内容并构建新的Object,而无需深入到String hell。
使用Array.map()
将服务器响应转换为所需的行数组,然后编写一个新的Object:
const results = {
data: [{
Country: "Australia",
Price: 174,
Discount: 23
},
{
Country: "Canada",
Price: 502,
Discount: 17
},
{
Country: "France",
Price: 242,
Discount: 37
}, {
Country: "Germany",
Price: 102,
Discount: 42
}
]
}
const rows = results.data.map(row => [row.Country, row.Price, row.Discount]);
var data3 = {
"headers": ["Dimension 1", "Metric 1", "Metric 2"],
"rows": rows
};
console.log(data3);