使用RxJS过滤对象的对象

时间:2016-11-07 22:16:07

标签: javascript angular rxjs

我有以下流,我想过滤并保留只有真实的参数(布尔值)。

{
  "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)

2 个答案:

答案 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 });
  }, {})
})
相关问题