开发者

Javascript loop json for value and apply if condition met

If I had the following JSON,

[{},{"param":"#content","value":"K2-12M","quantity":1,"q_id":3,"clear":1}
{"param":"#content","value":"K2-12F","quantity":2,"q_id":3,"clear":0}]

In js/jquery, how would I loop through, and if any of the items have "clear":0, then set 开发者_高级运维ALL items to "clear":0 ?


var clear;
for( var i=0, l=json.length; i<l; i++ ){
    if( 0 === json[i].clear ){
        clear = true;
        break;
    }
}

if( clear ){
    for( i=0; i<l; i++) {
        json[i].clear = 0;
    }
}

or using jQuery (this is less efficient):

$( json ).filter(
    function( ix, obj ){
        return 0 === obj.clear;
    }
).length
    && $( json ).each(
        function( ix, obj ){
            obj.clear = 0;
        }
    );


Nested for-loop:

for(var i = 0, l = json.length; i < l; i++ ){
    if(json[i].clear == 0){
        for(var x = 0; x < l; x++) {
            json[x].clear = 0;
        }
        break;
    }
}

Fiddle for your fiddling pleasure.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜