【问题标题】:JavaScript | UnderscoreJS: Map Items in One Collection to Properties in AnotherJavaScript | UnderscoreJS:将一个集合中的项目映射到另一个集合中的属性
【发布时间】:2015-07-19 16:49:29
【问题描述】:

将一个集合中的项目映射到另一个集合中的项目属性

我希望使用 [任何方式,包括] UnserscoreJS 将一个集合中的对象映射到不同集合中另一个对象的属性。例如,将[ { id: 998, ... }, ... ] 映射到[ { thing: 998, ... }, ... ]。换句话说:

if (collection1[i].id === collection2[n].thing)
    collection2[n].thing = collection1[i];

当然,我们可以使用 map 函数 + 用于第二个集合的迭代器来编写此代码——但我的问题是:

有没有办法利用另一个 [比如说] UnderscoreJS 的功效来高效而优雅地完成这项工作?

【问题讨论】:

    标签: javascript collections mapping underscore.js


    【解决方案1】:

    分辨率

    使用 Underscore 的 findWhere 方法,使用从映射函数中获得的 Id 从集合中提取适当的项目:

    var collection1 = [
        { id: 997, type: 'thing' },
        { id: 998, type: 'thing' },
        { id: 999, type: 'thing' },
        { id: 1000, type: 'thing' }
    ];
    var collection2 = [
        { id: 111, type: 'otherThing', thing: 1000 },
        { id: 222, type: 'otherThing', thing: 999 },
        { id: 333, type: 'otherThing', thing: 998 },
        { id: 444, type: 'otherThing', thing: 997 }
    ];
    
    _.map(collection2, function(otherThing){
        var thingId = otherThing.thing
          , thing = _.findWhere(collection1, { id: thingId });
        if (thing && thingId === thing.id) { otherThing.thing = thing; }
        return otherThing;
    });
    

    这正是我一直在寻找的,我希望它可以帮助您节省一些时间,因为有时这就像在翻阅大型图书馆的文档时大海捞针一样。

    愉快的编码

    【讨论】:

    • 你应该使用 _.each 因为你不是真正的映射(地图的结果没有分配给任何东西)。 thingId === thing.id 在 if 语句中是多余的。此外,thing 将设置为 collection1 中的对象,而不是 id。
    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多