簡體   English   中英

使用RxJS過濾對象的對象

[英]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"]
}

這是我嘗試處理此問題時的提示:

  • 我嘗試使用地圖,但沒有成功。 我猜是因為它是一個對象而不是數組。
  • 該對象中的所有鍵和值都是動態的,因此我無法使用它們來操作對象。
  • flatMap()對我有幫助,但是我不知道該怎么做,因為我不知道鍵的名稱。
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM