I have a JavaScript object which contains 2 objects with different true/false Boolean and wanted to filter out the first object as it has all false values.
If in any scenario, any key is true then it should retain, and shouldn't filter out the data object.
I wanted to keep the 2nd object only based on any true value, as you can see it has some 'true' values.
Let me explain it further, as you could see the first object of 'data' which has all the Boolean values as 'false' should be omitted and end result should have the 2nd data object only as it's some 'true' values.
"data": [{
"Products": "Mobile",
"Australia": false,
"Austria": false,
"Belgium": false,
"Canada": false,
"China": false,
"India": false,
"Poland": false,
"Brazil": false,
"US": false
},
{
"Products": "Tablet",
"Australia": false,
"Austria": true,
"Belgium": false,
"Canada": false,
"China": false,
"India": true,
"Poland": false,
"Brazil": true,
"US": false
}]
End result should be like this only, it should filter the first object because of all false values.
"data": [{
"Products": "Tablet",
"Australia": false,
"Austria": true,
"Belgium": false,
"Canada": false,
"China": false,
"India": true,
"Poland": false,
"Brazil": true,
"US": false
}]
Any suggestion using raw JavaScript or Underscore.js is welcome.
Use filter
and some
.
data.filter( // Filter the data array by
function(product) { // looking at each product in it
return Object.keys(product) // and for that product's keys
.some( // see if any of the
function(key) { // keys
return product[key] === true; // have a value of true
}
)
;
}
)
A version using underscore:
var result = _.filter(data, function(product){
return _.some(product, function(value){
return _.isBoolean(value) && value;
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.