[英]Grouping Json/XML collection using lodash
我有以下查詢以便選擇銷售訂單行的項目,單位和數量:
var urlBestSoldItemDaily = sharedProperties.fooApi +
"/salesinvoice/SalesInvoices?$expand=SalesInvoiceLines&" +
"$select=SalesInvoiceLines/ItemCode,SalesInvoiceLines/UnitCode,SalesInvoiceLines/Quantity&"
結果是這樣的:
<entry>
<id>https://foo/api/salesinvoice/SalesInvoices(guid'607897fa-44aa-4626-a151-1b084bc9d149')</id>
<m:inline>
<feed>
<title type="text">SalesInvoiceLines</title>
<id>https://foo/api/salesinvoice/SalesInvoices(guid'607897fa-44aa-4626-a151-1b084bc9d149')/SalesInvoiceLines</id>
<entry>
<id>https://foo/api/salesinvoice/SalesInvoiceLines(guid'2cdf60c3-3430-4d6c-a58a-b7e96f9d6be6')</id>
<content type="application/xml">
<m:properties>
<d:ItemCode>IND43007</d:ItemCode>
<d:Quantity m:type="Edm.Double">2</d:Quantity>
<d:UnitCode>box</d:UnitCode>
</m:properties>
</content>
</entry>
</feed>
</m:inline>
我想對項目單位進行分組,然后使用lodash選擇按數量排序的結果列表的前10名。 我嘗試使用以下方法進行分組,但不起作用:
var list = _.groupBy(data.d.results, 'SalesInvoiceLines.ItemCode, SalesInvoiceLines.UnitCode');
如何進行分組,這樣我就可以得到具有分組總數的分組項目和單位的集合?
您如何做到的示例:
var sales = [
{itemCode: "0001", quantity: 2, unitItem: "box" },
{itemCode: "0002", quantity: 2, unitItem: "box" },
{itemCode: "0003", quantity: 3, unitItem: "boxx" },
{itemCode: "0004", quantity: 3, unitItem: "boxxx"},
{itemCode: "0005", quantity: 1, unitItem: "boxxx"}
];
/*
* I want to perform grouping on item-unit and then select the top 10
* of the result list sorted by quantity, using lodash.
*/
var calcQuantities = function(sales) {
var sum = function(total, curr) {
return total + curr.quantity;
};
return _.reduce(sales, sum, 0);
};
var toQuantitySale = function(sales) {
return {
quantity: calcQuantities(sales),
sales : sales
};
};
var sortDesc = function(sale) {
return -sale.quantity;
};
// Steps
var groupedSales = _.groupBy(sales, 'unitItem')
var quantitySales = _.map(groupedSales, toQuantitySale)
var sortedSales = _.sortBy(quantitySales, sortDesc)
var top10Sales = _.take(sortedSales, 10)
console.log(top10Sales);
// shorter
top10Sales =
_.chain(sales)
.groupBy('unitItem')
.map(toQuantitySale)
.sortBy(sortDesc)
.take(10)
.value()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.