gpt4 book ai didi

javascript - 使用 lodash 对 Json/XML 集合进行分组

转载 作者:行者123 更新时间:2023-12-03 07:54:59 26 4
gpt4 key购买 nike

我有以下查询来选择销售订单行的项目、单位和数量:

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>

我想对 item-unit 进行分组,然后使用 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()

关于javascript - 使用 lodash 对 Json/XML 集合进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34835760/

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