29

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?

4

5 回答 5

43

使用someArray 方法为数组的每个值测试您的函数:

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

顺便说一句,不要扩展Object.prototype

于 2013-10-10T17:48:44.247 回答
6

-- 对于财产 --

if(prop in Obj)  
//or
Obj.hasOwnProperty(prop)

-- 对于价值 ---

使用“Object.prototype.hasValue = ...”对于 js 来说将是致命的,但Object.defineProperty允许您使用enumerable:false定义属性 (默认)

Object.defineProperty(Object.prototype,"hasValue",{
   value : function (obj){
              var $=this;
              for( prop in $ ){
                  if( $[prop] === obj ) return prop;
              }
              return false;
           }
});

仅用于实验测试 NodeList 是否具有 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
于 2015-02-23T17:58:07.057 回答
4

对于数组,当然你必须浏览该数组for

for(var i = 0 ; i < yourArray.length; i++){
    if(yourArray[i].hasOwnProperty("name") && yourArray[i].name === "yourValue") {
     //process if true
    }
} 
于 2013-10-10T17:00:58.337 回答
0

通常你会使用类似的东西Object.first

// search for key "foo" with value "bar"
var found = !!Object.first(test, function (obj) {
    return obj.hasOwnProperty("foo") && obj.foo === "bar";
});

假设Object.first找不到匹配项时会返回一些虚假值。

Object.first不是本机功能,而是检查流行的框架,它们一定有一个。

于 2013-10-10T16:58:38.370 回答
0

这是检查对象是否具有属性但未设置属性值的另一种解决方案。也许属性值有 0、null 或空字符串。

array.forEach(function(e){
 if(e.hasOwnProperty(property) && Boolean(e[property])){
  //do something
 }
 else{
  //do something else
 }
});

Boolean() 是这里的诀窍。

于 2015-11-19T08:34:42.513 回答