I have an object that has several fields that could potentially get shifted to true for a user (think like a list of achievements). If I had an object like {one: true, two: false, three: true}
, how would I be able to escape the execution of the function (because not all the keys are true)? This is what I have tried so far:
for (var key in achis) {
if (achis.hasOwnProperty(key)) {
if (key === false) {
cb && cb();
return;
}
}
}
achievements.update({userId: achis.userid}, {$set: {all: true}}, function(err) {
if (err) {
console.log(err);
}
cb && cb();
return;
});
How would I be able to only update the acheivements doc field "all" to true if all the key values in achis is "true" like this: {one: true, two: true, three: true}
I have an object that has several fields that could potentially get shifted to true for a user (think like a list of achievements). If I had an object like {one: true, two: false, three: true}
, how would I be able to escape the execution of the function (because not all the keys are true)? This is what I have tried so far:
for (var key in achis) {
if (achis.hasOwnProperty(key)) {
if (key === false) {
cb && cb();
return;
}
}
}
achievements.update({userId: achis.userid}, {$set: {all: true}}, function(err) {
if (err) {
console.log(err);
}
cb && cb();
return;
});
How would I be able to only update the acheivements doc field "all" to true if all the key values in achis is "true" like this: {one: true, two: true, three: true}
5 Answers
Reset to default 2Array every()
with a truth check is a good way to do the test when you reference the keys of the Object.
var obj = {
a: true,
b: true
}
var isAllTrue = Object.keys(obj).every( function (key) {
return obj[key]===true;
});
console.log(isAllTrue);
You appear to already have the basic logic except you're paring the key
instead of the value
that you reference using that key obj[key]
.
Since the property tests are all synchronous, you can put it into a simple function like this:
function testAllProperties(obj, val) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (obj[key] !== val) {
return false;
}
}
}
return true;
}
if (testAllProperties(achis, true)) {
// all properties are true
} else {
// some properties are not true
}
Array.prototype.every()
is ideal for your solution.
var o1 = {one: true, two: false, three: true},
o2 = {one: true, two: true, three: true},
CB = _ => console.log("I am doing something because the object is all true"),
runCB = o => Object.keys(o).every(k => o[k]) && CB();
runCB(o1);
runCB(o2);
The shortest method available in newer browsers would be:
var obj = { a: true, b: true }
var allTrue = Object.values(obj).every(val => val);
key
just gives you the property name. If you want to get the value use archis[key]
.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745242315a4618254.html
评论列表(0条)