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?
The first way is to invoke object. hasOwnProperty(propName) . The method returns true if the propName exists inside object , and false otherwise. hasOwnProperty() searches only within the own properties of the object.
You can use the JavaScript in operator to check if a specified property/key exists in an object. It has a straightforward syntax and returns true if the specified property/key exists in the specified object or its prototype chain. Note: The value before the in keyword should be of type string or symbol .
JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.
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
.
-- 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With