我有JSON数据,我试图以以下格式存储在2D数组中:
[2009-01,324, 1075, 940, 441, 1040, 898, 1343]
[2009-02 295, 958, 904, 434, 1038, 793, 1246 ]
上面的符号视觉表示道歉。我有JSON数据,我使用for循环来获取密钥及其值,但我不知道如何将其存储在二维数组中。我在概念上正在努力。我是初学者,真的想要一些指导。谢谢。
<script>
$.getJSON('data.json', function (data) {
var response = data;
var listOfTimes = new Array();
for(i = 0; i < 2; i++){ //number of rows...
for(j = 0; j< 8; j++){ //number of columns
for(key in response){
....not sure what to do here
}
}
}
});
</script>
JSON数据采用以下格式:
"2009-01": {
"bbcfour": 324,
"bbcnews24": 1075,
"bbcone": 940,
"bbcthree": 441,
"bbctwo": 1040,
"cbbc": 898,
"cbeebies": 1343
},
"2009-02": {
"bbcfour": 295,
"bbcnews24": 958,
"bbcone": 904,
"bbcthree": 434,
"bbctwo": 1038,
"cbbc": 793,
"cbeebies": 1246
}
答案 0 :(得分:1)
尝试遍历所有日期&amp;然后在他们的属性上内循环
<script>
$.getJSON('data.json', function (data) {
var arr = [];
for(var date in data){
var items = [];
for(var key in date){
items.push(date[key]);
}
arr.push(items);
}
console.log(arr); // the requested array
});
</script>
答案 1 :(得分:0)
var response = data;
var listOfTimes = new Array();
for(i = 0; i < 2; i++){ //number of rows...
listOfTimes[i]=response[i];
for(j = 0; j< 8; j++){ //number of columns
listOfTimes[i]=repsonse[i][j];
}
}
答案 2 :(得分:0)
我认为你正在寻找这个,它将根据你的地图创建一个数组数组。不确定为什么不能使用数组数据模型。 (注意那个$ .each,它需要jQuery)
var resp = {"2009-01": {
"bbcfour": 324,
"bbcnews24": 1075,
"bbcone": 940,
"bbcthree": 441,
"bbctwo": 1040,
"cbbc": 898,
"cbeebies": 1343
},
"2009-02": {
"bbcfour": 295,
"bbcnews24": 958,
"bbcone": 904,
"bbcthree": 434,
"bbctwo": 1038,
"cbbc": 793,
"cbeebies": 1246
}};
var arrays = [];
for (mainKey in resp) {
var array = [];
arrays.push(array);
array.push(mainKey);
$.each(resp[mainKey], function(key, value) {
array.push(value)
});
};
答案 3 :(得分:0)
var mainobj={
"2009-01": {
"bbcfour": 324,
"bbcnews24": 1075,
"bbcone": 940,
"bbcthree": 441,
"bbctwo": 1040,
"cbbc": 898,
"cbeebies": 1343
},
"2009-02": {
"bbcfour": 295,
"bbcnews24": 958,
"bbcone": 904,
"bbcthree": 434,
"bbctwo": 1038,
"cbbc": 793,
"cbeebies": 1246
}
};
var my2darray=[];
for (var date in mainobj) {
var temparray=[date];
for(val in mainobj[date]){
temparray.push(mainobj[date][val]);
}
my2darray.push(temparray);
}
console.log(my2darray);
输出:
[["2009-01", 324, 1075, 940, 441, 1040, 898, 1343],
["2009-02", 295, 958, 904, 434, 1038, 793, 1246 ]]