JavaScript | UnderscoreJS:将一个集合中的项目映射到另一个集合中的属性
JavaScript | UnderscoreJS: Map Items in One Collection to Properties in Another
将一个集合中的项目映射到另一个集合中的属性项目
我希望使用 [任何方法,包括] UnserscoreJS 将一个集合中的对象映射到另一个集合中的另一个对象的 属性。例如,将 [ { id: 998, ... }, ... ]
映射到 [ { thing: 998, ... }, ... ]
。换句话说:
if (collection1[i].id === collection2[n].thing)
collection2[n].thing = collection1[i];
当然,我们可以使用 map
函数 + 第二个集合的迭代器来编写它——但我的问题是:
有没有办法利用另一个 [say] UnderscoreJS 功效来高效优雅地完成此任务?
分辨率
使用 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;
});
这正是我要找的东西,我希望它能帮助您节省一些时间,因为有时候翻阅大型图书馆的文档就像大海捞针一样。
编码愉快
将一个集合中的项目映射到另一个集合中的属性项目
我希望使用 [任何方法,包括] UnserscoreJS 将一个集合中的对象映射到另一个集合中的另一个对象的 属性。例如,将 [ { id: 998, ... }, ... ]
映射到 [ { thing: 998, ... }, ... ]
。换句话说:
if (collection1[i].id === collection2[n].thing)
collection2[n].thing = collection1[i];
当然,我们可以使用 map
函数 + 第二个集合的迭代器来编写它——但我的问题是:
有没有办法利用另一个 [say] UnderscoreJS 功效来高效优雅地完成此任务?
分辨率
使用 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;
});
这正是我要找的东西,我希望它能帮助您节省一些时间,因为有时候翻阅大型图书馆的文档就像大海捞针一样。
编码愉快