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.
精彩评论