如果对象包含 true key,则返回布尔 true 值,而不返回值

use*_*133 4 javascript object filter

如果我的对象包含具有真值的键,我真的很困惑如何返回简单的真/假。我不想返回键或值本身,只是返回它确实包含真实值的断言。

例如

var fruits = { apples: false, oranges: true, bananas: true }
Run Code Online (Sandbox Code Playgroud)

这个对象有一个真正的价值。我不在乎哪一个是真的……我只想能够返回,true因为那里有真正的价值。

我当前的解决方案["oranges", "bananas"]不返回true

Object.keys(fruits).filter(function(key) {
    return !!fruits[key]
})
Run Code Online (Sandbox Code Playgroud)

ggo*_*len 6

正如Giuseppe Leo 的回答所暗示的那样,您可以使用Object.values(键在这里并不重要)来生成要调用的对象值的数组Array#includes

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));
Run Code Online (Sandbox Code Playgroud)

如果Object.keys允许但Object.values不允许includes,您可以使用类似以下内容的内容Array#reduce

var fruits = {apples: false, oranges: true, bananas: true};
console.log(Object.keys(fruits).reduce((a, e) => a || fruits[e] === true, false));
Run Code Online (Sandbox Code Playgroud)

如果您无权访问任何内容(或者不喜欢reduce上面的方法不会短路),您始终可以编写一个函数来迭代键以查找特定的目标值(以保持函数可重用)对于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));
Run Code Online (Sandbox Code Playgroud)