【问题标题】:Getting property value by property key in array of object where each object has different property keys通过对象数组中的属性键获取属性值,其中每个对象具有不同的属性键
【发布时间】:2021-03-17 18:13:22
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: arrays ecmascript-6 properties


    【解决方案1】:

    componentNames 上使用Array#find,搜索包含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') );

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多