gpt4 book ai didi

javascript - 通过键将数组中的对象推送到不同的数组

转载 作者:行者123 更新时间:2023-11-30 09:21:05 26 4
gpt4 key购买 nike

我正在尝试将一个对象数组推送到另一个现有的对象数组。

例子:

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 匹配。所以它看起来像这样:

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。

最佳答案

您可以遍历 invoices,然后通过验证 InvoiceId 是否相同来找到 invoiceLines 中的所有匹配项。下面的示例代码

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)

关于javascript - 通过键将数组中的对象推送到不同的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51620190/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com