Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if the object has a property and value in javascript

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?

like image 923
Joey Hipolito Avatar asked Oct 10 '13 16:10

Joey Hipolito


People also ask

How do you check if a property is present in an object?

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.

How do you check if an object has a key value?

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 .

Does object have property JavaScript?

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.


2 Answers

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.

like image 66
Bergi Avatar answered Oct 19 '22 09:10

Bergi


-- 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
like image 6
bortunac Avatar answered Oct 19 '22 08:10

bortunac