查找 Value in Object 是否存在于数组中

Find whether Value in Object exists within an array

我正在尝试查找值 roomTypeFilter 是否存在于数组中的对象中。然后我想根据值 roomTypeFilter 是否存在来执行条件语句。

下面是我的代码

function includes(k) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] === k || (this[i] !== this[i] && k !== k)) {
            return true;
        }
    }
    return false;

}
var dayValue = this.ui.dayConstraintList.val();
var arr = [courseTemplate.get('dayConstraints')[dayValue]];
console.log(arr);
arr.includes = includes;
console.log(arr.includes('roomTypeFilter'));

第一个 console.log return 是数组中的对象。

第二个 console.log returns false,在这种情况下,因为 roomTypeFilter 存在于我想要 return 'true' 的对象中但我不确定该怎么做,任何帮助将不胜感激。

不使用 includes,而是使用 hasOwnProperty。查看 here 了解有关 hasOwnProperty 的更多信息。从它的名字来看它是不言自明的——它本质上是 returns 一个关于对象是否有 属性 的布尔值。即,在您的情况下,您将使用:

arr[0].hasOwnProperty('roomTypeFilter');

您可以使用 hasOwnProperty 方法检查对象是否包含 roomTypeFilter 属性.

...
if (this[i].hasOwnProperty(k)) {
    ...
}
...

您可以重构 includes 函数以使用

array.prototype.some

some() executes the callback function once for each element present in the array until it finds one where callback returns a truthy value... If such an element is found, some() immediately returns true.

这是一个例子。

var arr = [
  {
    roomTypeFilter: {
      name: 'foo'
    }
  },
  ["roomTypeFilter", "foo"],
  "roomTypeFilter foo"
]

function includes(arr, k) {
  return arr.some(function(item) {
    return item === Object(item) && item.hasOwnProperty(k);
  })
}

console.log("Does arr includes roomTypeFilter ? - ", includes(arr, 'roomTypeFilter'))