arrays - 通过对象数组中的属性键获取属性值,其中每个对象具有不同的属性键
问题描述
对于从 API 获得的给定名称(例如“large_banner”),我需要在我的应用程序中导入相应的组件(在本例中为“LargeBanner”)。
所以我创建了一个数组,将每个 API 名称连接到每个组件名称:
componentNames: [
{ index: 'ButtonSection' },
{ large_banner: 'LargeBanner' },
{ small_banner: 'SmallBanner' }
]
给定“large_banner”(例如),我如何在这个数组中获得“LargeBanner”?有没有一种简单的方法可以在 ES6 中实现这一点?
解决方案
使用Array#find
oncomponentNames
搜索包含key
(例如large_banner
)的数组项。
然后,如果存在,则返回此属性的值:
const componentNames = [
{ index: 'ButtonSection' },
{ large_banner: 'LargeBanner' },
{ small_banner: 'SmallBanner' }
];
const getComponent = name => {
const component = componentNames.find(c => c[name]);
return component && component[name];
}
console.log( getComponent('index') );
console.log( getComponent('large_banner') );
console.log( getComponent('small_banner') );
console.log( getComponent('invalid') );
如果您可以使用JSON
对象映射名称,如下所示,这会更简单:
const componentNames = {
index: 'ButtonSection',
large_banner: 'LargeBanner',
small_banner: 'SmallBanner'
};
const getComponent = name =>
componentNames[name];
console.log( getComponent('index') );
console.log( getComponent('large_banner') );
console.log( getComponent('small_banner') );
console.log( getComponent('invalid') );
推荐阅读
- tensorflow - 使用数据集生成器进行 tf.keras 预测
- google-cloud-platform - 使用 Ansible 在 Google Cloud Storage 存储桶上启用对象生命周期管理
- testing - JMeter - 从文件添加 json 响应并将其设置为获取请求中的响应正文
- here-api - 如何找到两个位置之间的道路距离?
- c# - 使用 ASP.NET Core 使用 async 和 await 进行异步编程
- swift - Swift 用子协议中的具体类型替换关联类型
- javascript - Ember 更新页面标题
- xml - 如何在 XSD 中定义本地类型?
- javascript - 千位逗号分隔符问题仅验证最后 3 位数字
- java - BulkOperations upsert 抛出无效的 BSON 字段名称