确定对象是否在javascript中具有属性和值 [英] Determine if the object has a property and value in javascript

查看:79
本文介绍了确定对象是否在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}]

到那里,有一个对象数组,现在我想在对象内部进行搜索,如果对象包含我想要的内容,则返回true.

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.

我试图这样做:

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?

推荐答案

使用 some数组方法,以针对该数组的每个值测试您的函数:

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

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

Btw, don't extend Object.prototype.

这篇关于确定对象是否在javascript中具有属性和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆