【发布时间】: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