目标是在“allInvoices”数组中查找“selectedIds”数组中具有相应invoiceId的所有对象。
我目前正在使用lodash并实现如下。我想知道是否有更优雅的方法使用lodash,链接或其他任何方式执行此任务。
var selectedIds = [
{ invoiceId: 2, customerId: 34 },
{ invoiceId: 4, customerId: 49}
];
var allInvoices = [
{
id: 2,
name: 'Ron',
date: '2015-14-12'
},
{
id: 3,
name: 'Harry'
},
{
id:4,
name: 'snowpiercer'
},
{
id:5,
name: 'birdman'
},
{
id:6,
name: 'superman'
}
];
var result = [];
_.forEach(selectedIds, function(myId) {
var eachInvoice = _.find(allInvoices,{id: myId.invoiceId});
result.push(eachInvoice);
});
console.log(result);
答案 0 :(得分:1)
这是另一种方法:
_(allInvoices)
.groupBy('id')
.at(_.pluck(selectedIds, 'invoiceId'))
.flatten()
.value()
答案 1 :(得分:0)
它不够整洁;但这会保存任何嵌套循环(由_.find
引起):
var pluckedIds = _.pluck( selectedIds, "invoiceId" ); // [2,4]
var result = _.filter( allInvoices, function ( invoice ) {
return pluckedIds.indexOf( invoice.id ) !== -1;
});