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 :...

问题:

var attributeList = [];

var attributeEmail = {
    Name : 'email',
    Value : 'email@mydomain.com'
};
var attributePhoneNumber = {
    Name : 'phone_number',
    Value : '+15555555555'
};
attributeList.push(attributeEmail);
attributeList.push(attributePhoneNumber);

result is:

Attributes: Array(2)
1: {Name: "phone_number", Value: "+15555555555"}
2: {Name: "email", Value: "email@mydomain.com"}

I need find email in attributeList

var email = getEmail(attributeList);
console.log(email); // email@mydomain.com

private getEmailAttribute(attributeList) {
    // Name: "email"...
    return ????;
}

回答1:

You can use .find with destructuring assignment to get the object which has the Name of email. Then, once you have retrieved the object you can get the email by using the .Value property.

See example below:

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

As a side note. To declare a function in javascript, you do not use the private keyword. Instead, you can use the function keyword as I have above.


回答2:

You can get the email by using filter(), map() and shift(). This method is safe, it will not throw and will return undefined if it doesn't find the email object.

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


回答3:

Use Array.prototype.find() to get the object whose Name = "email" and then return its 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);

  • 发表于 2019-02-13 16:27
  • 阅读 ( 283 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除