如何根据多个值对数据数组进行分组?

时间:2019-03-01 16:23:32

标签: arrays group-by lodash

我想根据类型和type_id对数据进行分组 这是数组

var addArray = [
                    {
                        "id": 24,
                        "language_id": 3,
                        "type": "service",
                        "type_id": 2,
                        "key": "service seeker",
                        "value": " need service"
                    },
                    {
                        "id": 23,
                        "language_id": 3,
                        "type": "service",
                        "type_id": 2,
                        "key": "phone",
                        "value": "phone number"
                    },
                    {
                        "id": 24,
                        "language_id": 3,
                        "type": "service",
                        "type_id": 7,
                        "key": "tester",
                        "value": "service tester"
                    }
                    {
                        "id": 19,
                        "language_id": 3,
                        "type": "offer",
                        "type_id": 4,
                        "key": "source",
                        "value": "resource"
                    }
                ]

我尝试过let result = _.groupBy(addArray,'type'),它根据类型对数据进行分组,但是我需要按类型以及type_id进行分组

预期产量

1 个答案:

答案 0 :(得分:1)

如果您需要基于两个或多个属性的平面分组,请使用_.groupBy()回调将这些属性组合为字符串:

const addArray = [{"id":24,"language_id":3,"type":"service","type_id":2,"key":"service seeker","value":" need service"},{"id":23,"language_id":3,"type":"service","type_id":2,"key":"phone","value":"phone number"},{"id":24,"language_id":3,"type":"service","type_id":7,"key":"tester","value":"service tester"},{"id":19,"language_id":3,"type":"offer","type_id":4,"key":"source","value":"resource"}]

const result = _.groupBy(addArray, o => `${o.type}-${o.type_id}`)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

如果您需要进行多级分组,请先按type分组,然后用_.values()映射组,然后再按type_id分组:

const { flow, partialRight: pr, groupBy, mapValues } = _

const fn = flow(
  pr(groupBy, 'type'),
  pr(mapValues, g => groupBy(g, 'type_id'))
)

const addArray = [{"id":24,"language_id":3,"type":"service","type_id":2,"key":"service seeker","value":" need service"},{"id":23,"language_id":3,"type":"service","type_id":2,"key":"phone","value":"phone number"},{"id":24,"language_id":3,"type":"service","type_id":7,"key":"tester","value":"service tester"},{"id":19,"language_id":3,"type":"offer","type_id":4,"key":"source","value":"resource"}]

const result = fn(addArray)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>