ImmutableJS - 过滤嵌套Map {List(Map {...})}

时间:2017-08-11 09:18:47

标签: javascript reactjs functional-programming immutability immutable.js

给出以下数据结构。

let hall = Map({
  tables: Map({
    t1: Map({
      playlist: List(
        Map({
          songid: 'target'
        })
      )
    }),
    t2: Map({
      playlist: List(
        Map({
          songid: 'not me'
        })
      )
    })
  })
});

如何遍历每个表(t1,t2,...)并使用songid === 'target'删除列表中的项目,以便最终得到:

let expected_hall = Map({
  tables: Map({
    t1: Map({
      playlist: List()
    }),
    t2: Map({
      playlist: List(
        Map({
          songid: 'not me'
        })
      )
    })
  })
});

尝试以下无济于事:

let res = hall;
hall.get('tables').entrySeq().forEach(e => {
  res = res.updateIn(['tables', e[0], 'playlist'], list => list.filter(songinfo => songinfo.songid === 'target'));
});

// or using  hall.get('tables').map(...)

感谢所有帮助。

2 个答案:

答案 0 :(得分:1)



let hall = Map({
  tables: Map({
    t1: Map({
      playlist: List.of(
        Map({
          songid: 'target'
        })
      )
    }),
    t2: Map({
      playlist: List.of(
        Map({
          songid: 'not me'
        })
      )
    })
  })
});




您使用List的方式,应该是List.of(...)或List([])

我会这样做:



const hall2 = hall.update("tables", tables => (
  tables.map(table => (
    table.update("playlist", playlist => playlist.filter(p => p.get("songid")!=="not me"))
  ))
));




您更新tables属性,遍历每个表,更新播放列表属性并按照不是"不是我"

的每个项目过滤播放列表

答案 1 :(得分:-1)

List#filter的文档

  

返回一个新的List,其中只包含谓词函数返回true的值。

因此,我们必须返回songid target

的列表



let res = hall;
hall.get('tables').keySeq().forEach(e => {
  res = res.updateIn(['tables', e, 'playlist'], list => list.filter(info => info.get("songid") !== "target"));
});




相关问题