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

标签 javascript angularjs odata 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>

我想对 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/

相关文章:

javascript - 使用 Chartjs.org V2.7 过滤图例项

javascript - Bootstrap选项卡刷新页面

c# - 在 C# 中使用 OData 服务不起作用

javascript - 对象中的条件变量

php - Javascript 和 PHP 中的字符编码是否不同?

angularjs - 使用 NodeJS、Express 和 Passport-ldapauth 进行 LDAP 身份验证

c# - 通过 Web API 2 将 ASP.NET 身份(用户管理)添加到 OData

odata - OData 查询能否指定引用嵌套实体的过滤器?

javascript - 防止 gmail 剥离 href、target 和 id 属性

angularjs - 使用带有 Angular $http 的 curl 请求