问题:
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);