我想将i设置为来自json标准的第一项的0,例如。如果标准是绿色,在这种情况下,我将从3开始...如果标准=蓝色它将从2开始......我需要将其设置为从0或1开始是否是..还如何计算总数标准,例如。绿色总数是2,蓝色= 1,红色= 2 ......提前感谢!
var myBox_html ="";
var i = 0;
function createDiv(1x,2x,3x) {
A = '<something>'+1x;
B = '<something>'+2x;
C = '<something>'+3x;
myBox_html += '<something-more>'+A+B+C;
}
criteria // is a parameter from url, in this case means green
get_it = function(doc) {
var jsonData = eval('(' + doc + ')');
for (var i=0; i<jsonvar.name.length; i++) {
var 1x = jsonvar.name[i].1;
var 2x = jsonvar.name[i].2;
var 3x = jsonvar.name[i].3;
if (1x == criteria){
var Div = createDiv(1x,2x,3x);
} else {null}
}
document.getElementById("myBox").innerHTML = myBox_html;
}
get_it();
json应该是这样的:
var jsonvar = {"name":[{"1":"red","2":"round","3":"fruit"},{"1":"red","2":"squared","3":"box"},{"1":"blue","2":"squared","3":"box"},{"1":"green","2":"squared","3":"box"},{"1":"green","2":"pear","3":"fruit"}]};
答案 0 :(得分:0)
考虑几种解决方案:
1:在服务器端生成标准分组的JSON响应。 E.g。
var jsonvar = '{"name":{
"red": [{"1":"red","2":"round","3":"fruit"}, {"1":"red","2":"squared","3":"box"}],
"blue": [{"1":"blue","2":"squared","3":"box"}],
"green":[{"1":"green","2":"squared","3":"box"}, {"1":"green","2":"pear","3":"fruit"}]}}';
2:将JSON数组转换为上面定义的条件分组格式。以下是此类分组的示例例程:
function group_elements (arr) {
var result = {};
for (var i=0; i < arr.length; i++) {
if (!result[arr[i][1]]) {
result[arr[i][1]] = [];
}
result[arr[i][1]].push(arr[i]);
}
return result;
}
两种解决方案都允许您仅迭代过滤的记录并计算组的长度。