繁体   English   中英

如何通过特定属性在数组中查找特定值元素?

[英]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 ,然后returnValue

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM