[英]Filter object of object with RxJS
我有以下信息流,我想过滤并仅保留true(boolean)的参数。
{
"colors": {
"red": "",
"yellow": true,
"green": false
},
"size": {
"t5": true,
"t10": "",
"t20": true
}
}
我需要输出看起来像这样:
{
"colors": ["yellow"],
"size": ["t5,t20"]
}
这是我尝试处理此问题时的提示:
this.form.valueChanges
.debounceTime(400)
.flatMap(x => Object.values(x))
.subscribe(console.log)
这不是rxjs问题,只是普通的js映射:
getTruthyKeys(obj: any): Array<string> {
return Object.keys(obj).filter(key => obj[key] === true);
}
mainKeysToTruthyLists(obj: any): Array<{key: string, truthy: Array<string>}> {
let result = {};
Object.keys(obj).forEach(key => result[key] = getTruthyKeys(obj[key]);
return result;
}
现在您可以将其作为地图应用于您的信息流:
this.form.valueChanges
.debounceTime(400)
.map(mainKeysToTruthyLists)
.subscribe(console.log)
这实际上不是RxJS问题。 RxJS在这里要做的就是map
。 这可以通过Object.entries
完成:
this.form.valueChanges
.debounceTime(400)
.map(obj => {
return Object.entries(obj)
.reduce((newObj, [key, subObj]) => {
const subArr = Object.entries(subObj)
.filter(([, subValue]) => subValue)
.map(([subKey]) => subKey);
return Object.assign(newObj, { [key]: subArr });
}, {})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.