【问题标题】:lodash groupby item.product_id possible?lodash groupby item.product_id 可能吗?
【发布时间】:2021-10-15 19:39:20
【问题描述】:

我有一个这样的数组:

    Array [
      Object {
        "item": Object {
          "amount": 1,
          "price": 29.99,
          "product_id": 5,
          "product_name": "Calvin klein Bag",
          "username": "Ester71",
        },
        "type": "NORMAL",
      },
      Object {
        "item": Object {
          "amount": 1,
          "price": 29.99,
          "product_id": 3,
          "product_name": "Calvin klein Bag",
          "username": "Ester71",
        },
        "type": "NORMAL",
      },
      Object {
        "item": Object {
          "amount": 1,
          "price": 29.99,
          "product_id": 5,
          "product_name": "Calvin klein Bag",
          "username": "Ester71",
        },
        "type": "NORMAL",
      },
    ],

我想要 groupby product_id。但它不起作用。

这是一个带有颜色的示例。它可以工作,如果我删除上面数组中的项目,那么它也可以工作,但项目必须在那里做。

var data = [{
  "name": "jim",
  "color": "blue",
  "age": "22"
}, {
  "name": "Sam",
  "color": "blue",
  "age": "33"
}, {
  "name": "eddie",
  "color": "green",
  "age": "77"
}];

console.log(
  _.chain(data)
    // Group the elements of Array based on `color` property
    .groupBy("color")
    // `key` is group's name (color), `value` is the array of objects
    .map((value, key) => ({ color: key, users: value }))
    .value()
);

那么我现在如何按 item.product_id 分组?

【问题讨论】:

    标签: javascript reactjs react-native expo lodash


    【解决方案1】:

    你可以试试这个

    const data = [
      {
        "item":  {
          "amount": 1,
          "price": 29.99,
          "product_id": 5,
          "product_name": "Calvin klein Bag",
          "username": "Ester71",
        },
        "type": "NORMAL",
      },
       {
        "item":  {
          "amount": 1,
          "price": 29.99,
          "product_id": 3,
          "product_name": "Calvin klein Bag",
          "username": "Ester71",
        },
        "type": "NORMAL",
      },
       {
        "item": {
          "amount": 1,
          "price": 29.99,
          "product_id": 5,
          "product_name": "Calvin klein Bag",
          "username": "Ester71",
        },
        "type": "NORMAL",
      },
    ]
    
    const groupBy = (product) => product.item.product_id
    
    console.log(
      _.chain(data)
      .groupBy(groupBy)
      .map((value, key) => ({ product_id: key, products: value }))
      .value()
    );
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      相关资源
      最近更新 更多