在数组内的对象属性上是相等的

时间:2015-11-24 23:03:22

标签: javascript jquery

我有对象

var emailData = new {};
emailData.Id;
emailData.EmailAddress;

稍后在代码I中使用emailData对象填充数组

 var emailDataArr = new Array();
 emailDataArr.push(..someobject...);

如何检查EmailAddress数组中emailDataArr属性上的任何对象是否等于某个字符串?

2 个答案:

答案 0 :(得分:1)

您可以使用Array.prototype.some来解决这个问题。这是一个例子:

function hasAddress( array, address ) {
    return array.some(function(data) {
        return data.EmailAddress === address;
    });
}

var emailDataArr = new Array();
emailDataArr.push(/* Data */);
console.log( hasAddress( emailDataArr, 'SomeString' ) );

答案 1 :(得分:1)

您可以转到http://jsfiddle.net/du2b6r1y/查看实时示例。

//https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/create
var emailData = {}; //Please use Object.create instead of new {}; if that not possible you simple should use {} 

// you can also 
var emailDataArr = [
    {
        Id: 1,
        EmailAdress : "nadf@asdfa"
    },
    {
        Id: 2,
        EmailAdress : "adfasd@asdfa"
    },
    {
        Id: 3,
        EmailAdress : null
    }
]; //please avoid new in all you javascript code if possible

var filter = emailDataArr.filter(function(email) {
return typeof email.EmailAdress === "string";
}); 

console.log(filter);
//you will get only emails that are strings
//[object, object];

//or you can go over each of them and compare them

emailDataArr.forEach(function(email) {
    if(typeof email.EmailAdress === "string") {
        //do your thing
        console.log("is a string");
    }
});