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.
3 Answers 3
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');
-
When I try
console.log(arr[0].hasOwnProperty('roomTypeFilter'));
I getUncaught TypeError: Cannot read property 'hasOwnProperty' of undefined
mcclosa– mcclosa2016年08月17日 13:25:18 +00:00Commented Aug 17, 2016 at 13:25 -
1Then your
arr[0]
must be undefined. Whichever object you would like check if it contains the function you're looking for, place that atarr[0]
. The syntax is essentiallyobject.hasOwnProperty('function/property')
Ted– Ted2016年08月17日 13:27:14 +00:00Commented Aug 17, 2016 at 13:27 -
Ahh yes, the function this is within is called on two different circumstances, it's initially undefined, but defined in another circumstance.mcclosa– mcclosa2016年08月17日 13:31:11 +00:00Commented Aug 17, 2016 at 13:31
-
Great :) Glad i could help, if you have any further questions, let me knowTed– Ted2016年08月17日 13:37:41 +00:00Commented Aug 17, 2016 at 13:37
You can use hasOwnProperty method to check if object contains roomTypeFilter
property.
...
if (this[i].hasOwnProperty(k)) {
...
}
...
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'))
Explore related questions
See similar questions with these tags.
hasOwnProperty
console.log(!arr.filter(d => d.hasOwnProperty('roomTypeFilter')).length);