javascript - 按 1 个键对对象数组进行分组,并拆分 1 个属性
问题描述
我有这个对象数组
test = [
{
'id': 1,
'name': 'XYZ'
'value': 10
'quantity': 100
},
{
'id': 1,
'name': 'XYZ'
'value': 20
'quantity': 200
},
{
'id': 2,
'name': 'ABC'
'value': 11
'quantity': 111
},
{
'id': 2,
'name': 'ABC'
'value': 22
'quantity': 222
}
]
我想按 id 对它们进行分组,但名称和 {value, quantity} 分开,如下所示:
result = {
1: [
'name': 'XYZ'
'items': [
{
'value': 10
'quantity': 100
},
{
'value': 20
'quantity': 200
}
]
],
2: [
'name': 'ABC'
'items': [
{
'value': 11
'quantity': 111
},
{
'value': 22
'quantity': 222
}
]
],
}
知道我该怎么做吗?我可以按 id 分组,但我无法提取名称。谢谢
解决方案
我认为您可以reduce()
在这种情况下使用将元素分组id
const test = [
{
'id': 1,
'name': 'XYZ',
'value': 10,
'quantity': 100,
},
{
'id': 1,
'name': 'XYZ',
'value': 20,
'quantity': 200,
},
{
'id': 2,
'name': 'ABC',
'value': 11,
'quantity': 111,
},
{
'id': 2,
'name': 'ABC',
'value': 22,
'quantity': 222,
}
];
const res = test.reduce((ac, {id, name, ...rest}) => ({...ac, [id]: ac[id] ? [...ac[id], rest] : [rest] }), {});
console.log(res)
推荐阅读
- sql - Why is this SQL Function TicksToDateTime non-deterministic? and how to make it deterministic?
- reactjs - 缺少用户和文档 ID,但其他属性可用
- c# - 已解决:C# MemoryStream 转换为字节数组,然后到 base64 字符串删除 RTL 字符
- java - 在 cassandra 表中插入增量序列号
- c# - 如何根据 WindowChrome 的颜色设置窗口标题的颜色
- c++ - 如何确保在定义之前声明 C++ 函数(如 override 关键字)?
- angular - 角日期管
- php - 从服务访问变量时出错
- python - 为什么我在简单的 2 输出 2 输入网络中在 Keras 中得到 6 个参数?
- java - 使用 jsp:forward 转发到另一个页面