I'm trying to check if a value exists in an array property, an alert should pop up, if not it should log in the console. With my current code this is the results i'm getting
User Data Arrary
[{"primary_contact":"+1111111111","secondary_contact":null},{"primary_contact":"+2222222222","secondary_contact":"+2"}]
Code
for (let r = 0; r < this.global.userData.length; r++) {
if (this.global.userData[r].primary_contact === this.formattedNumber1) {
alert('Phone Number has been used already');
} else {
console.log('push data')
}
}
When I sent +1111111111
as the formattedNumber1 the alert pops up, but when I set +2222222222
the alert doesn't pop up and it writes in the console but it should be able to pop up an alert cos +2222222222
also exist in the array
答案 0 :(得分:3)
您的数组无效。我相信这是一个错字。请参阅下面的示例代码,其中已固定了阵列。
另一种替代解决方案可以是使用Array.Some():
let arr = [{
"primary_contact": "+1111111111",
"secondary_contact": null
}, {
"primary_contact": "+2222222222",
"secondary_contact": "+2"
}];
function contactExists(contact) {
return arr.some(function(el) {
return el.primary_contact === contact;
});
}
console.log(contactExists('+1111111111')); // true
console.log(contactExists('+2222222222')); // true