【问题标题】:How to get subset of an object array filtered on items of (sub)property array如何在(子)属性数组的项目上获取对象数组过滤器的子集
【发布时间】:2019-09-14 21:24:33
【问题描述】:

从(对象)数组中提取子集的最佳方法(可能是异步的)是什么?我们要在其中过滤/搜索也是数组的属性项?

比方说,从下面的列表中,我们只想要“basecolors”属性(子)数组中具有“Green”的项目。我们会得到一个包含 5 个项目的数组:1、7、8、11、17。

例子:

export const COLORS: Color[] = [
    { name: 'Aqua', hex: '#00FFFF', basecolors: ['Blue', 'Green'] },        // 1
    { name: 'Black', hex: '#000000', basecolors: ['Black'] },       // 2
    { name: 'Blue', hex: '#0000FF', basecolors: ['Blue'] },     // 3
    { name: 'Brown', hex: '#A52A2A', basecolors: ['Red'] },     // 4
    { name: 'Fuchsia', hex: '#FF00FF', basecolors: ['Blue', 'Red'] },       // 5
    { name: 'Gray', hex: '#808080', basecolors: ['Black', 'White'] },       // 6
    { name: 'Green', hex: '#008000', basecolors: ['Green'] },       // 7
    { name: 'Lime', hex: '#00FF00', basecolors: ['Green'] },        // 8
    { name: 'Maroon', hex: '#800000', basecolors: ['Red'] },        // 9
    { name: 'Navy', hex: '#000080', basecolors: ['Blue'] },     // 10
    { name: 'Olive', hex: '#808000', basecolors: ['Green', 'Red'] },        // 11
    { name: 'Orange', hex: '#FFA500', basecolors: ['Red', 'Yellow'] },      // 12
    { name: 'Pink', hex: '#FFC0CB', basecolors: ['Red'] },      // 13
    { name: 'Purple', hex: '#800080', basecolors: ['Blue', 'Red'] },        // 14
    { name: 'Red', hex: '#FF0000', basecolors: ['Red'] },       // 15
    { name: 'Silver', hex: '#C0C0C0', basecolors: ['Black', 'White'] },     // 16
    { name: 'Teal', hex: '#008080', basecolors: ['Blue', 'Green'] },        // 17
    { name: 'White', hex: '#FFFFFF', basecolors: ['White'] },       // 18
    { name: 'Yellow', hex: '#FFFF00', basecolors: ['Yellow'] }      // 19
];

现在我们可以将对象传递给名为:colorsList - 例如:

colorsList: Color[] = COLORS;

现在我们过滤得到结果子数组,其中只有包含“Green”的“basecolors”项 我正在寻找这样的东西:

const greenColorsList: Color[] = this.colorsList.filter(item => item.basecolors.contains('Green'));

【问题讨论】:

  • 您分享的代码有什么问题?看起来它应该做到这一点?
  • 现在我知道出了什么问题 - 多种语言的受害者。 ' item.basecolors.contains('Green') 应该是:item.basecolors.includes('Green')。
  • 这和角度无关,这只是一个JS问题;)

标签: javascript arrays filter


【解决方案1】:
const greenColorsList: Color[] = this.colorsList.filter(item => item.basecolors.includes('Green'));

异步方式 - 例如:

const searchPhrase$ = new BehaviorSubject<string>('');

searchPhrase$.next('Green');

const items$ = searchPhrase$.pipe(
  map((phrase = '') => phrase.length > 0
    ? this.colorsList
      .filter(({ basecolors }) => basecolors.indexOf(phrase) >= 0).slice(0)
    : this.colorsList
  )
);

items$.subscribe(colors => {
  this.greenColorsList = colors;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-13
    • 2019-10-01
    • 2020-07-11
    • 1970-01-01
    • 2016-05-02
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多