开发者

How to set i to 0 of the first item from a json criteria

I want to set i to 0 of the first item from a json criteria, eg. if the criteria is green in this case the i will start from 3... if criteria = blue it will start on 2... i need to set it to start from 0 or 1 whether it is.. also how to count total of a criteria, eg. green total is 2,, blue=1, red=2... thanks in advance!

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 should look like this:

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"}]};


Consider several solutions:

1: Generate criteria-grouped JSON response on the server-side. 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: Convert you JSON array to criteria-grouped format as defined above. Here is sample routine for such a grouping:

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;
}

Both solutions allows you to iterate only filtered records and count length of group.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜