Javascript 如何过滤redux存储的RxJS可观察对象?

Javascript 如何过滤redux存储的RxJS可观察对象?,javascript,filter,rxjs,observable,Javascript,Filter,Rxjs,Observable,我正在使用RxJS观察我的redux存储何时发生更改,如下所示: 我有一个像这样的对象: { commands: [ {key: 'arrows', isEnabled: true, activeState: 1, numStates: 2 }, {key: 'focus', isEnabled: false, hotKey: 'f' }, {key: 'geometry', isEnabled: true, activeState: 1, numStates: 2

我正在使用RxJS观察我的redux存储何时发生更改,如下所示:

我有一个像这样的对象:

 {
  commands: [
    {key: 'arrows', isEnabled: true, activeState: 1, numStates: 2 },
    {key: 'focus', isEnabled: false, hotKey: 'f' },
    {key: 'geometry', isEnabled: true, activeState: 1, numStates: 2 },
    {key: 'goToEnd', isEnabled: true },
此“命令”数组中的每个项目都成为GUI中的工具栏按钮。我已经编写了更改每个命令的各个属性的代码,但现在我需要监听并订阅每个命令的更改


如何获取此流并通过
commandkey
对其进行过滤,以便仅当焦点命令更改其
isEnabled
和/或
activeState
属性更改时才会触发可观察对象?

您可以
根据您的条件过滤可观察对象。当然,您需要利用Array.prototype中的
.map()
.filter()
函数:

store$.filter(store => {
    return store
        .commands
        .filter(command => command.key == 'focus' && command.isEnabled)
        .length; //if length is greater than 0, means condition is met.
})

好吧,我想办法做我想做的事。请参阅下面的代码。还有更好的办法吗

const store = Rx.Observable.create(function(observer) {
  let state = { commands: [
    {key: 'arrows', isEnabled: true, activeState: 0, numStates: 2 },
    {key: 'focus', isEnabled: false, hotKey: 'f' },
    {key: 'geometry', isEnabled: true, activeState: 1, numStates: 2 },
    {key: 'goToEnd', isEnabled: true }]
  };

  observer.next(state);

  state = { commands: [
    {key: 'arrows', isEnabled: true, activeState: 1, numStates: 2 },
    {key: 'focus', isEnabled: true, hotKey: 'f' },
    {key: 'geometry', isEnabled: true, activeState: 1, numStates: 2 },
    {key: 'goToEnd', isEnabled: true }]
  };

  observer.next(state);

  state = { commands: [
    {key: 'arrows', isEnabled: true, activeState: 1, numStates: 2 },
    {key: 'focus', isEnabled: true, hotKey: 'f' },
    {key: 'geometry', isEnabled: true, activeState: 1, numStates: 2 },
    {key: 'goToEnd', isEnabled: true }]
  };

  observer.next(state);
});


const subscribe = store.map( state => {
    const commands = state.commands.filter( cmd => cmd.key === 'arrows' );
    if( commands.length == 0 ) {
       return undefined; 
    }
    const result = {
       isEnabled: commands[0].isEnabled,
       activeState: commands[0].activeState,
    };
    return result;
})
.distinctUntilChanged( ( a, b ) => a.isEnabled === b.isEnabled && a.activeState === b.activeState )
.subscribe(val => console.log(val));
此处的工作示例:


基本上,我只在指定的选定命令键的isEnabled或activeState属性更改时(本例中的箭头)才会收到通知。

您可以使用distinctUntilChanged运算符仅在值更改时收到通知

store.map(state => 
   state.commands.filter(cmd => cmd.key === 'focus')[0].isEnabled)
  .distinctUntilChanged()

我无法运行该代码。见:@mareknows.com yeap编辑。抱歉,我正在电话上查看,所以没有意识到它是一个对象。我在这里尝试了:但是distinctUntilChanged()似乎不起作用。请注意,在链接的示例中,我得到了两次相同的结果。啊,我看到我需要将一个函数传递到distinctunitrichanged以进行比较。返回的对象的默认比较不正确。是的,默认比较只是“==”。很高兴它现在起作用了。