I'm really stuck on how to return a simple true/false IF my object contains a key with a true value. I do not want to return the key or value itself, just an assertion that it does contain a true value.
Eg
var fruits = { apples: false, oranges: true, bananas: true }
There's a true value in this object. I don't care which one is true... I just want to be able to return true
because there is a true value.
My current solution returns ["oranges", "bananas"]
not true
Object.keys(fruits).filter(function(key) {
return !!fruits[key]
})
You can use Object.values
(keys aren't important here) to produce an array of the object's values to call Array#includes
on:
const fruits = {apples: false, oranges: true, bananas: true}; console.log(Object.values(fruits).includes(true)); // test the sad path console.log(Object.values({foo: false, bar: 42}).includes(true));
If Object.keys
is permitted but Object.values
and includes
aren't, you can use something like Array#reduce
:
var fruits = {apples: false, oranges: true, bananas: true}; console.log(Object.keys(fruits).reduce((a, e) => a || fruits[e] === true, false));
If you don't have access to anything (or don't like that the reduce
approach above doesn't short-circuit), you can always write a function to iterate through the keys to find a particular target value (to keep the function reusable for other targets than true
):
function containsValue(obj, target) { for (var key in obj) { if (obj[key] === target) { return true; } } return false; } var fruits = {apples: false, oranges: true, bananas: true}; console.log(containsValue(fruits, true));
Try with Array.prototype.some() :
The
some()
method tests whether at least one element in the array passes the test implemented by the provided function.
var fruits = { apples: false, oranges: true } var r = Object.keys(fruits).some(function(key) { return !!fruits[key] }) console.log(r);
Though, instead of Object.keys()
, it is better to use Object.values() to iterate the objects value directly:
The
Object.values()
method returns an array of a given object's own enumerable property values, in the same order as that provided by afor...in
loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
var fruits = { apples: false, oranges: true } var r = Object.values(fruits).some(f => f) console.log(r);
正如您想知道是否有任何值是true
:
Object.values(fruits).includes(true)
You could check with Boolean
as callback for Array#some
.
const has = o => Object.values(o).some(Boolean); var a = {}, b = { oranges: true, apples : false }, c = { oranges: false, apples : false }; [a, b, c].forEach(o => console.log(has(o)));
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.