Remove key based object from array of objects
Below is the json:
var data= {
'A' : {
'Total' : 123,
'Cricket' : 76,
'Football' : 12,
'Hockey' : 1,
'None' : 10
},
'B' : {
'Total': 123,
'Cricket': 76,
'Football': 12,
'Hockey': 1,
'None': 10
},
'C' : {
'Total': 0,
'Cricket': 76,
'Football': 12,
'Hockey': 1,
'None': 10
}
}
I want to remove C where total is zero,
$.each(json, function (key, value) {
if (value.Total === 0) {
//delete
}
});
I tried different ways but didn't work
+3
source to share
2 answers
Use delete
to remove a property on an object.
var json = {
'A': {
'Total': 123,
'Cricket': 76,
'Football': 12,
'Hockey': 1,
'None': 10
},
'B': {
'Total': 123,
'Cricket': 76,
'Football': 12,
'Hockey': 1,
'None': 10
},
'C': {
'Total': 0,
'Cricket': 76,
'Football': 12,
'Hockey': 1,
'None': 10
}
}
$.each(json, function(key, value) {
if (value.Total === 0) {
delete json[key];
}
});
console.log(json);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
+5
source to share
$(function(){
var data= {
'A' : {
'Total' : 123,
'Cricket' : 76,
'Football' : 12,
'Hockey' : 1,
'None' : 10
},
'B' : {
'Total': 123,
'Cricket': 76,
'Football': 12,
'Hockey': 1,
'None': 10
},
'C' : {
'Total': 0,
'Cricket': 76,
'Football': 12,
'Hockey': 1,
'None': 10
}
}
$.each(data, function (key, value) {
if (value.Total === 0) {
delete data[key];
}
});
console.log(data);
});
Fiddle: http://jsfiddle.net/ef3Le1en/
0
source to share