首页 > 解决方案 > 如何获取对象数组中键的值?

问题描述

我有一个结构如下的对象数组:

import icon1 from '!!raw-loader!../../../icon1.svg';
import icon2 from '!!raw-loader!../../../icon2.svg';
import icon3 from '!!raw-loader!../../../icon3.svg';
import icon4 from '!!raw-loader!../../../icon4.svg';
import icon5 from '!!raw-loader!../../../icon5.svg';

export const CustomIcons = [
  {
    home: 'icon1',
    homeIcon: (icon)
  },
  {
    series: 'icon2',
    seriesIcon: (icon2)
  },
  {
    explorer: 'icon3',
    explorerIcon: (icon3)
  },
  ...
];

在我的模块的构造函数中,我想使用如下值:

export class IconRegistryModule {
  constructor(iconRegistry: MatIconRegistry, sanitizer: DomSanitizer) {
    CustomIcons.forEach(icon => {
      iconRegistry.addSvgIconLiteral(Object.keys(icon)[0], sanitizer.bypassSecurityTrustHtml(Object.keys(icon)[1]));
    });
  }
}

因此,对于 forEarch 的第一次运行,addSvgIconLiteral 方法应该如下所示:

iconRegistry.addSvgIconLiteral('the value of the key home', sanitizer.bypassSecurityTrustHtml('the value of the key homeIcon');

标签: javascriptangulartypescriptdata-structureshigher-order-functions

解决方案


使用它来获取数组中的对象键。

CustomIcons.map((data) => {
console.log(Object.keys(data));
});

推荐阅读