Reputation: 11864
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 ????;
}
Upvotes: 1
Views: 56
Reputation: 50674
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.
Upvotes: 1
Reputation: 36564
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);
Upvotes: 1
Reputation: 13964
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);
Upvotes: 3