gpt4 book ai didi

javascript - 使用lodash groupBy函数对数组中的对象进行分类

转载 作者:行者123 更新时间:2023-12-01 00:47:54 24 4
gpt4 key购买 nike

我有一个产品数组,每个产品都有一个类别对象。我需要按类别组织并包含类别对象。 GroupBy 函数仅包含一个参数。

产品系列

const data = [   
{id: 1, 'name': 'produto1', category: {id: 1, name: 'shirts', description: 'super roupa'}},
{id: 2, 'name': 'produto2', category: {id: 1, name: 'shirts', description: 'super roupa'}},
{id: 3, 'name': 'produto3', category: {id: 2, name: 'jackets', description: 'super jackets'}},
{id: 4, 'name': 'produto4', category: {id: 2, name: 'jackets', description: 'super jackets'}},
]

预期结果:

[
{
category: {id: 1, name: 'clothes', description: 'super roupa'},
products:[{id:1, name: 'produt1'}, {id: 2, name: 'produto1'} ]
},
{
category: {id: 2, name: 'jackets', description: 'super jackets'},
products:[{id:3, name: 'produt3'}, {id: 4, name: 'produto4'} ]
},
]

最佳答案

category.id 进行分组,然后通过从组中第一项获取 category 并省略 将每个组映射到一个对象所有产品的类别:

const data = [{"id":1,"name":"produto1","category":{"id":1,"name":"shirts","description":"super roupa"}},{"id":2,"name":"produto2","category":{"id":1,"name":"shirts","description":"super roupa"}},{"id":3,"name":"produto3","category":{"id":2,"name":"jackets","description":"super jackets"}},{"id":4,"name":"produto4","category":{"id":2,"name":"jackets","description":"super jackets"}}]

const result = _(data)
.groupBy('category.id')
.map(group => ({
category: _.head(group).category,
products: _.map(group, o => _.omit(o, 'category'))
}))
.value()

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

或者与 lodash/fp 等效的 _.flow() 函数:

const { flow, groupBy, map, head, omit } = _

const fn = flow(
groupBy('category.id'),
map(group => ({
category: head(group).category,
products: map(omit('category'), group)
}))
)

const data = [{"id":1,"name":"produto1","category":{"id":1,"name":"shirts","description":"super roupa"}},{"id":2,"name":"produto2","category":{"id":1,"name":"shirts","description":"super roupa"}},{"id":3,"name":"produto3","category":{"id":2,"name":"jackets","description":"super jackets"}},{"id":4,"name":"produto4","category":{"id":2,"name":"jackets","description":"super jackets"}}]

const result = fn(data)

console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

关于javascript - 使用lodash groupBy函数对数组中的对象进行分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57234403/

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