1
var attributeList = [];

var attributeEmail = {
    Name : 'email',
    Value : '[email protected]'
};
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 protected]"}

I need find email in attributeList

var email = getEmail(attributeList);
console.log(email); // [email protected]

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

3 Answers 3

3

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 protected]'
};
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);

Sign up to request clarification or add additional context in comments.

Comments

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 protected]'},{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.

Comments

1

Use Array.prototype.find() to get the object whose Name = "email" and then return its Value.

var attributeList = [];

var attributeEmail = {
    Name : 'email',
    Value : '[email protected]'
};
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.