JavaScript | UnderscoreJS:将一个集合中的项目映射到另一个集合中的属性

时间:2015-07-19 16:49:30

标签: javascript collections mapping underscore.js

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

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

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

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

有没有办法利用另一个[说] UnderscoreJS功效来有效和优雅地实现这一目标?

1 个答案:

答案 0 :(得分:0)

分辨率

使用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;
});

这正是我所寻找的,我希望它能帮你节省一些时间,因为有时它可能就像在大海捞针查找大型图书馆的文件一样。

快乐编码