Reputation: 3166
I wanted to check if the an object has a property of something and its value is equal to a certain value.
var test = [{name : "joey", age: 15}, {name: "hell", age: 12}]
There you go, an array of objects, now I wanted to search inside the object and return true if the object contains what I wanted.
I tried to do it like this:
Object.prototype.inObject = function(key, value) {
if (this.hasOwnProperty(key) && this[key] === value) {
return true
};
return false;
};
This works, but not in an array. How do I do that?
Upvotes: 33
Views: 101621
Reputation: 361
Here is another solution for checking if the object has the property but the value of property is not set. Maybe the property value has 0, null or an empty string.
array.forEach(function(e){
if(e.hasOwnProperty(property) && Boolean(e[property])){
//do something
}
else{
//do something else
}
});
Boolean() is the trick here.
Upvotes: 0
Reputation: 664395
Use the some
Array method to test your function for each value of the array:
function hasValue(obj, key, value) {
return obj.hasOwnProperty(key) && obj[key] === value;
}
var test = [{name : "joey", age: 15}, {name: "hell", age: 12}]
console.log(test.some(function(boy) { return hasValue(boy, "age", 12); }));
// => true - there is a twelve-year-old boy in the array
Btw, don't extend Object.prototype
.
Upvotes: 49
Reputation: 4808
-- for the property --
if(prop in Obj)
//or
Obj.hasOwnProperty(prop)
-- for the value ---
Using "Object.prototype.hasValue = ..." will be FATAL for js but Object.defineProperty let you define properties with enumerable:false (default)
Object.defineProperty(Object.prototype,"hasValue",{
value : function (obj){
var $=this;
for( prop in $ ){
if( $[prop] === obj ) return prop;
}
return false;
}
});
just for experiment test if a NodeList has an Element
var NL=document.QuerySelectorAll("[atr_name]"),
EL= document.getElementById("an_id");
console.log( NL.hasValue(EL) )
// if false then #an_id has not atr_name
Upvotes: 6
Reputation: 16764
For array, of course you have to browse that array with for
for(var i = 0 ; i < yourArray.length; i++){
if(yourArray[i].hasOwnProperty("name") && yourArray[i].name === "yourValue") {
//process if true
}
}
Upvotes: 4
Reputation: 57709
Typically you'll use something like Object.first
:
// search for key "foo" with value "bar"
var found = !!Object.first(test, function (obj) {
return obj.hasOwnProperty("foo") && obj.foo === "bar";
});
Assuming that Object.first
will return some falsy value when it doesn't find a match.
Object.first
is not a native function but check on of the popular frameworks, they're bound to have one.
Upvotes: 0