[英]How to get subset of an object array filtered on items of (sub)property array
What would be the best approach (possibly async) for extracting a sub-set from an array (of objects) where we want to filter/search for items of a property that also is an array? 从(对象的)数组中提取子集的最佳方法(可能是异步的)是什么,我们要过滤/搜索也是数组的属性的项?
Lets say, from following list we want only items that have 'Green' in the "basecolors" property (sub)array. 可以说,从下面的列表中,我们只需要在“ basecolors”属性(子)数组中具有“绿色”的项目。 And we would get a resulting array of 5 items: 1, 7, 8, 11, 17. 我们将得到一个包含5个项目的结果数组:1、7、8、11、17。
Example: 例:
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
];
Now we can pass the object to array named: colorsList - eg: 现在我们可以将对象传递给名为:colorsList的数组-例如:
colorsList: Color[] = COLORS;
and now we filter to get resulting sub-array, which will have only items of 'basecolors' containing 'Green' I am looking for something like this: 现在我们进行过滤以获得结果子数组,该子数组将仅包含包含“绿色”的“ basecolors”项,我正在寻找类似以下内容的东西:
const greenColorsList: Color[] = this.colorsList.filter(item => item.basecolors.contains('Green'));
const greenColorsList: Color[] = this.colorsList.filter(item => item.basecolors.includes('Green'));
Async way - eg: 异步方式-例如:
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;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.