【问题标题】:ImmutableJS: Convert List to indexed MapImmutableJS:将列表转换为索引地图
【发布时间】:2015-11-20 15:48:37
【问题描述】:

这个问题是关于 Immutable.js 库的。

我有一个List<T>,其中T{name: string, id: number}。我想将其转换为Map<number, T>,并将idT 转换为键。使用标准方法toMap 给我一个带有顺序索引的Map,并且没有办法挂在那里。并且没有像indexBy 或其他方法这样的方法。该怎么做?

【问题讨论】:

    标签: immutable.js


    【解决方案1】:

    你可以用这样的减速器来做到这一点:

    function indexBy(iterable, searchKey) {
        return iterable.reduce(
            (lookup, item) => lookup.set(item.get(searchKey), item),
            Immutable.Map()
        );
    }
    
    var things = Immutable.fromJS([
        {id: 'id-1', lol: 'abc'},
        {id: 'id-2', lol: 'def'},
        {id: 'id-3', lol: 'jkl'}
    ]);
    var thingsLookup = indexBy(things, 'id');
    thingsLookup.toJS() === {
      "id-1": { "id": "id-1", "lol": "abc" },
      "id-2": { "id": "id-2", "lol": "def" },
      "id-3": { "id": "id-3", "lol": "jkl" }
    };
    

    【讨论】:

    • 谢谢你的例子,我在这个问题上苦苦挣扎了几天
    猜你喜欢
    • 2020-12-04
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    相关资源
    最近更新 更多