![](/img/trans.png)
[英]How to find if an array element contains a specific value in JavaScript/jQuery?
[英]How to find specific value element in array by specific attribut?
var attributeList = [];
var attributeEmail = {
Name : 'email',
Value : 'email@mydomain.com'
};
var attributePhoneNumber = {
Name : 'phone_number',
Value : '+15555555555'
};
attributeList.push(attributeEmail);
attributeList.push(attributePhoneNumber);
结果是:
Attributes: Array(2)
1: {Name: "phone_number", Value: "+15555555555"}
2: {Name: "email", Value: "email@mydomain.com"}
我需要在attributeList
找到电子邮件
var email = getEmail(attributeList);
console.log(email); // email@mydomain.com
private getEmailAttribute(attributeList) {
// Name: "email"...
return ????;
}
您可以使用filter()
, map()
和shift()
获得电子邮件。 此方法是安全的, 不会抛出该 undefined
如果找不到该电子邮件对象,它将返回undefined
。
const attributeList = []; const attributeEmail = { Name : 'email', Value : 'email@mydomain.com' }; const attributePhoneNumber = { Name : 'phone_number', Value : '+15555555555' }; attributeList.push(attributeEmail); attributeList.push(attributePhoneNumber); function getEmailAttribute(attributes) { return attributes .filter(attr => attr.Name === 'email') .map(attr => attr.Value) .shift(); } const email = getEmailAttribute(attributeList); console.log(email);
使用Array.prototype.find()
获取其Name = "email"
的object
,然后return
其Value
。
var attributeList = []; var attributeEmail = { Name : 'email', Value : 'email@mydomain.com' }; var attributePhoneNumber = { Name : 'phone_number', Value : '+15555555555' }; attributeList.push(attributeEmail); attributeList.push(attributePhoneNumber); function getEmailAttribute(list){ let obj = list.find(item=> item.Name === "email") return obj && obj.Value; } let email = getEmailAttribute(attributeList); console.log(email);
您可以将.find
与解构分配一起使用,以获取具有电子邮件Name
的对象。 然后,一旦检索到对象,就可以使用.Value
属性获取电子邮件。
请参见下面的示例:
function getEmailAttribute(attributeList) { return attributeList.find(({Name}) => Name === "email").Value; } var attributeList = [{Name: 'email', Value: 'email@mydomain.com'},{Name: 'phone_number', Value: '+15555555555'}]; console.log(getEmailAttribute(attributeList));
作为旁注。 要在javascript中声明函数,请不要使用private
关键字。 相反,您可以像上面一样使用function
关键字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.