我的php脚本中有JSON字符串,如下所示:
var r.co = {
"A20018425":[
{"balance":"1390.31"}, // 1
{"balance":"1304.11"}, // 2
{"balance":"1188.11"}, // 3
{"balance":"1421.71"} // 4
],
"A25005922":[
{"balance":"1000"}, // 1
{"balance":"1000.86"}, // 2
{"balance":"986.32"}, // 3
{"balance":"988.96"}, // 4
{"balance":"980.26"}, // 5
{"balance":"980.16"} // 6 MAX
],
"A25005923":[
{"balance":"1001"}, // 1
{"balance":"1000.16"}, // 2
]
}
我不知道有多少AXXXXXXXX元素及其包含的元素数量。 要获得A元素,我使用下面的代码:
var accounts = [];
for(var key in r.co) {
if(r.co.hasOwnProperty(key)) {
accounts.push(key);
}
}
现在我知道我的A元素长度
var accounts_length = accounts.length; // 3 for example
现在我需要知道A:
中元素的最大长度var accounts_elements_length = [];
for (var c = 0; c < accounts.length; c++) {
accounts_elements_length.push(r.co[accounts[c]].length);
}
var accounts_elements_length_max = accounts_elements_length.max() // 6 For example
如何为图表获取此输出数组?
var outputData = [{
count: 1,
A20018425: 1390.31,
A25005922: 1000,
A25005923: 1001
}, {
count: 2,
A20018425: 1304.11,
A25005922: 1000.86,
A25005923: 1000.16
}, {
count: 3,
A20018425: 1188.11,
A25005922: 986.32
}, {
count: 4,
A20018425: 1421.71,
A25005922: 988.96
}, {
count: 5,
A25005922: 980.26
}, {
count: 6,
A25005922: 980.16
}
}];
谢谢!
答案 0 :(得分:2)
刚刚结合你的算法:
var outputData = [];
for (var key in r.co) {
if (r.co.hasOwnProperty(key)) {
var account_length = r.co[key].length;
for (var c = 0; c < account_length; c++) {
if (outputData[c] === undefined) {
outputData[c] = { count: c+1 };
}
outputData[c][key] = r.co[key][c].balance;
}
}
}
console.log(outputData);
答案 1 :(得分:1)
代码:
var outputData = [];
for (var i = 0; i < 6; i++) { // filter should be - i < accounts_elements_length_max
var temp = {
'count': i + 1
};
for (var j = 0; j < accounts.length; j++) {
if (r[accounts[j]][i]) temp[accounts[j]] = r[accounts[j]][i].balance;
}
outputData.push(temp);
}
请注意,我硬编码accounts_elements_length_max(6)。
我得到的输出:
[{
"count": 1,
"A20018425": "1390.31",
"A25005922": "1000",
"A25005923": "1001"},
{
"count": 2,
"A20018425": "1304.11",
"A25005922": "1000.86",
"A25005923": "1000.16"},
{
"count": 3,
"A20018425": "1188.11",
"A25005922": "986.32"},
{
"count": 4,
"A20018425": "1421.71",
"A25005922": "988.96"},
{
"count": 5,
"A25005922": "980.26"},
{
"count": 6,
"A25005922": "980.16"}]
工作fiddle