Reputation: 1445
I am trying to find whether the value roomTypeFilter
exists within an Object inside an array. I then want to perform conditional statements depending whether the value roomTypeFilter
exists or not.
Below is my code
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'));
The first console.log
returns an Object inside an array.
The second console.log
returns false
, in this case as roomTypeFilter
exists inside the Object I want to return 'true' but I am unsure how to do so, any help would be greatly appreciated.
Upvotes: 2
Views: 115
Reputation: 15293
You could refactor your includes
function to use
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.
Here is an example.
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'))
Upvotes: 1
Reputation: 1765
You can use hasOwnProperty method to check if object contains roomTypeFilter
property.
...
if (this[i].hasOwnProperty(k)) {
...
}
...
Upvotes: 1
Reputation: 756
Instead of using includes
, use hasOwnProperty
. Take a look here for more information on the hasOwnProperty
. It's pretty self-explanatory from its name - it essentially returns a boolean on whether or not the object has a property. I.e., in your case, you would use:
arr[0].hasOwnProperty('roomTypeFilter');
Upvotes: 1