我正在尝试将对象数组推到另一个现有的对象数组。
示例:
var invoices = [
{
InvoiceId: 2,
Contact: 'Jim',
InvoiceNumber: '3',
LineItems: []
},
{
InvoiceId: 1002,
Contact: 'Peter',
InvoiceNumber: '4' },
LineItems: []
}];
var invoiceLines = [
{ Id: 1003,
InvoiceId: 2 },
Amount: 1000,
{ Id: 1004,
InvoiceId: 2,
Amount: 1000,
{ Id: 1006,
InvoiceId: 1002,
Amount: 3000,}];
因此,我尝试将每个对象放入 invoiceLines 数组中,并将其推送到 invoices.Lineitems if InvoiceId < / strong>匹配。所以看起来像这样:
var result= [
{
InvoiceId: 2,
Contact: 'Jim',
InvoiceNumber: '3',
LineItems: [{
Id: 1003,
InvoiceId: 1002,
Amount: 1000},{
Id: 1004,
InvoiceId: 1002,
Amount: 1000}]
},
{
InvoiceId: 1002,
Contact: 'Peter',
InvoiceNumber: '4' },
LineItems: [{
Id: 1006,
InvoiceId: 1002,
Amount: 3000}]
}];
我尝试了以下方法:
var result = _({})
.merge(
_(flattenedinvoiceLines).groupBy("InvoiceId").value(),
_(invoices).groupBy("Id").value())
.values()
.flatten()
.value();
}
这只是推送到invoices数组,而不是invoice.LineItems。
答案 0 :(得分:2)
您可以遍历invoices
,然后通过验证invoiceLines
是否相同来找到InvoiceId
中的所有匹配项。下面的示例代码
var invoices = [
{
InvoiceId: 2,
Contact: 'Jim',
InvoiceNumber: '3',
LineItems: []
},
{
InvoiceId: 1002,
Contact: 'Peter',
InvoiceNumber: '4',
LineItems: []
}
];
var invoiceLines = [
{ Id: 1003,
InvoiceId: 2,
Amount: 1000
},
{ Id: 1004,
InvoiceId: 2,
Amount: 1000,
},
{ Id: 1006,
InvoiceId: 1002,
Amount: 3000
}
];
const result = invoices.map(invoice => {
invoice.LineItems = invoiceLines.filter((line) => line.InvoiceId === invoice.InvoiceId)
return invoice;
})
console.log(result)
答案 1 :(得分:2)
由于您使用的是Lodash,因此请使用:
_.map
遍历invoices
数组_.filter
根据invoiceLines
从InvoiceId: item.InvoiceId
中查找每条匹配的线_.extend
将每个经过过滤和匹配的invoiceLine
添加到LineItems
var invoices = [{
InvoiceId: 2,
Contact: 'Jim',
InvoiceNumber: '3',
LineItems: []
},
{
InvoiceId: 1002,
Contact: 'Peter',
InvoiceNumber: '4',
LineItems: []
}
];
var invoiceLines = [{
Id: 1003,
InvoiceId: 2,
Amount: 1000
},
{
Id: 1004,
InvoiceId: 2,
Amount: 1000
},
{
Id: 1006,
InvoiceId: 1002,
Amount: 3000
}
];
var mergedInvoices = _.map(invoices, function(item) {
_.extend(item.LineItems, _.filter(invoiceLines, { InvoiceId: item.InvoiceId }));
return item;
});
console.log(mergedInvoices);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
const invoices = [{
InvoiceId: 2,
Contact: 'Jim',
InvoiceNumber: '3',
LineItems: []
},
{
InvoiceId: 1002,
Contact: 'Peter',
InvoiceNumber: '4',
LineItems: []
}
];
const invoiceLines = [{
Id: 1003,
InvoiceId: 2,
Amount: 1000
},
{
Id: 1004,
InvoiceId: 2,
Amount: 1000
},
{
Id: 1006,
InvoiceId: 1002,
Amount: 3000
}
];
const mergedInvoices = _.map(invoices, item => {
_.extend(item.LineItems, _.filter(invoiceLines, { InvoiceId: item.InvoiceId }));
return item;
});
console.log(mergedInvoices);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>