Using Rxjs distinct operator to compare whole object with nesting

时间:2018-02-03 10:37:27

标签: json angular object rxjs rxjs5

I'm having an observable that passes me a json object on which I'm using the distinct operator. I don't want to have duplicates if the entire object is same as before. I can't just use a one comparator like id, as it's id might be same but it's content not.

So I'm currenty stringifying the object and then using distinct and it works fine

Is there a better way to do this?

someObservable
  .startWith(cachedCopy)
  .map(item => JSON.stringify(item))
  .distinct()
  .subscribe(item => {
      //I do some stuff!
     })

3 个答案:

答案 0 :(得分:2)

Actually I think using JSON.stringify() to compare whether two objects contain the same data is the easiest way to go. If you know the object identity must be different you could use pairwise().filter(pair => pair[0] !== pair[1]) (these must be two different object instances) but this really depends on your use-case and if you can guarantee such condition (usually not in my personal experience and comparing JSONs is "good enough").

Be aware that distinct() passes only really distinct items since the chain was created but in your description you say "duplicates if the entire object is same as before" which seems like you should be using distinctUntilChanged instead.

The distinctUntilChanged operator takes as an optional parameter a comparator function that you can use to check if two objects are the same:

.distinctUntilChanged((prev, curr) => JSON.stringify(prev) === JSON.stringify(curr))

答案 1 :(得分:1)

无论如何,在应用程序中都装有lodash时,您可以简单地使用lodash的isEqual()函数,该函数进行深度比较并与distinctUntilChanged()的签名完全匹配:

.distinctUntilChanged(isEqual),

或者如果您有_可用(现在不建议使用):

.distinctUntilChanged(_.isEqual),

答案 2 :(得分:0)

相反,我使用了Underscore.js Lib,它具有一个名为unique的功能,确实为我节省了 https://underscorejs.org/#uniq

1-安装它:

$ npm install underscore

2-叫它:

import { _ } from 'underscore';

3次使用:

this.allcate = _.uniq(this.allcate);