我有以下流,我想过滤并保留只有真实的参数(布尔值)。
{
"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)
答案 0 :(得分:3)
这不是一个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)
答案 1 :(得分:2)
这不是一个真正的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 });
}, {})
})