javascript - 如何通过特定属性在数组中查找特定值元素?
问题描述
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 ????;
}
解决方案
您可以使用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);
推荐阅读
- r - 在 R 中自动绘制不同的图形
- localstack - localstack v0.11.5 和 kcl v1.13.3
- forms - 从第二个子表单组合框中选择值时显示的访问 2016 参数值消息
- vb.net - 将自动完成中键入的文本限制为仅 VB.NET 中的有效字符串
- sql - 案例错误:在预期条件的上下文中指定的非布尔类型的表达式
- electron - 我如何解决为什么 electron-builder 没有创建一个有效的生产包
- 64-bit - 在 risc-v 架构中,mulh[[s]u] 操作返回的位是什么样的?
- django - 在 django 序列化程序响应中,如何摆脱 FileField 的绝对路径(media_url 前缀)?
- java - 为什么 setBackground 方法不改变不可编辑组合框的颜色?
- javascript - 如何使用香草javascript一次只检查一项?