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. And we would get a resulting array of 5 items: 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: 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:
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;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.