首页 > 解决方案 > 通过对象数组中的属性键获取属性值,其中每个对象具有不同的属性键

问题描述

对于从 API 获得的给定名称(例如“large_banner”),我需要在我的应用程序中导入相应的组件(在本例中为“LargeBanner”)。

所以我创建了一个数组,将每个 API 名称连接到每个组件名称:

componentNames: [
  { index: 'ButtonSection' },
  { large_banner: 'LargeBanner' },
  { small_banner: 'SmallBanner' }
]

给定“large_banner”(例如),我如何在这个数组中获得“LargeBanner”?有没有一种简单的方法可以在 ES6 中实现这一点?

标签: arraysecmascript-6properties

解决方案


使用Array#findoncomponentNames搜索包含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') );


推荐阅读