Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return boolean true value if object contains true key, not return the value

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.

E.g

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]
})
like image 730
user1486133 Avatar asked Oct 20 '25 15:10

user1486133


2 Answers

As Giuseppe Leo's answer suggests, 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));
like image 125
ggorlen Avatar answered Oct 23 '25 05:10

ggorlen


As you want to know if any of the values is true:

Object.values(fruits).includes(true)
like image 39
Giuseppe Leo Avatar answered Oct 23 '25 03:10

Giuseppe Leo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!