通过对象数组中的 属性 键获取 属性 值,其中每个对象都有不同的 属性 键

Getting property value by property key in array of object where each object has different property keys

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

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

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

给定“large_banner”(例如),如何在此数组中获取“LargeBanner”?在 ES6 中有一种简单的方法可以实现吗?

componentNames 上使用 Array#find,搜索包含 key 的数组项(例如 large_banner)。

然后,return这个属性的值如果存在:

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') );