首页 > 解决方案 > 如何通过特定属性在数组中查找特定值元素?

问题描述

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 ????;
}

标签: javascriptarraysfilterfind

解决方案


您可以使用filter()map()获取电子邮件shift()。这个方法是安全的,它不会抛出undefined,如果没有找到email对象就会返回。

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);


推荐阅读