假设我有一个客户对象数组,每个客户对象都有一个发票对象数组,每个发票都有一个invoice_items数组。
给出一个invoice_item_guid-我想返回带有特定GUID的1个唯一的invoice_item对象。
我不知道客户或发票,我不想创建一堆for循环。
例如:
客户
客户编号
发票
发票编号
invoice_items
invoice_item_guid
invoice_item_id
invoice_item_qty
我打算做类似复合查找的事情,像这样:
var i: invoice_item;
i = this.customers.find(c => c.invoices).find(inv => inv.invoice_items).find(item => item.invoice_item_guid === "someguid");
充其量,我会得到一个客户对象-但我真的想更深入地研究,并获得invoice_item对象(而不是客户)。
答案 0 :(得分:1)
我根据您的描述制作了一个虚拟数组。
以下解决方案应该可行,但可能不是最佳解决方案。
const customers = [{
customerId: 1,
invoices: [{
invoiceId: 1,
invoiceItems: [{
invoiceItemGuid: 1
}]
}]
},
{
customerId: 2,
invoices: [{
invoiceId: 2,
invoiceItems: [{
invoiceItemGuid: 2
}]
}]
}
]
const item = customers.flatMap(customer => customer.invoices).flatMap(invoice => invoice.invoiceItems).find(item => item.invoiceItemGuid === 2)
console.log(item)
答案 1 :(得分:0)
您可以使用Array.reduce和Array.map提取invoice_items数组并在其上使用Array.find。
let i = this.customers
.reduce((items, customer) => {
return items.concat(...customer.invoices
.map(invoice => invoice.invoice_items));
}, [])
.find(item => item.invoice_item_guid === 'someguid');
这是此解决方案的有效JSFiddle。
答案 2 :(得分:0)
编辑:使用'reduce
和find
方法更新了答案。
const findInvoiceItem = (data) => data
.reduce(
(acc, curr) => [
...acc,
...curr.invoices.reduce((acc_rec, curr_rec) => [
...acc_rec,
...curr_rec.invoice_items], [])
],
[]
)
.find(item => item.invoice_item_guid === "someguid");
const customers = [
{
customerid: 1,
invoices: [
{
invoiceid: 1,
invoice_items: [
{
invoice_item_id: 1,
invoice_item_qty: 2,
invoice_item_guid: "tempguid"
}
]
}
]
},
{
customerid: 2,
invoices: [
{
invoiceid: 2,
invoice_items: [
{
invoice_item_id: 2,
invoice_item_qty: 4,
invoice_item_guid: "someguid"
}
]
}
]
}
];
console.log(findInvoiceItem(customers));