javascript - 使用 groupBy 时向 JS 中的对象添加值
问题描述
当两个项目相同时,我正在使用mapValues
andgroupBy
进行分组和创建。keys
typeId
例如原始数据是
{
"Name": "One",
"typeId": 1
},
{
"Name": "Two",
"typeId": 2
},
{
"Name": "One Two",
"typeId": 1
},
{
"Name": "Three",
"typeId": 3
},
{
"Name": "Three Two",
"typeId": 3
}
并通过使用groupBy
我将具有匹配项的对象typeId
和来自“对象”omit
的typeId
值分组为...
const GroupedTypes = Object.entries(
_.mapValues(_.groupBy(data, 'typeID'), rlist =>
rlist.map(type => _.omit(type, 'typeID'))
)
);
按预期返回...
[
"1",
[
{
"Name": "One",
},
{
"Name": "One Two",
}
]
],
[
"2",
[
{
"Name": "Two",
}
]
],
[
"3",
[
{
"Name": "Three",
}
],
[
{
"Name": "Three Two",
}
]
]
但是,我还想从第一个对象中Name
的值添加Name
一个0
对象。因此以类似的东西结束。
[
"1",
"One",
[
{
"Name": "One",
},
{
"Name": "One Two",
}
]
],
[
"2",
"Two",
[
{
"Name": "Two",
}
]
],
[
"3",
"Three",
[
{
"Name": "Three",
}
],
[
{
"Name": "Three Two",
}
]
]
我一直在查看lodash
文档,但找不到有效的方法。我怎样才能做到这一点?
解决方案
您可以reduce
根据以下内容对项目进行分组typeId
:
const input=[{"Name":"One","typeId":1},{"Name":"Two","typeId":2},{"Name":"One Two","typeId":1},{"Name":"Three","typeId":3},{"Name":"Three Two","typeId":3}]
const merged = input.reduce((acc, { Name, typeId }) => {
acc[typeId] = acc[typeId] || [ typeId, Name, []];
acc[typeId][2].push({ Name });
return acc;
}, {})
console.log(Object.values(merged))
您需要创建一个累加器对象,每个对象都typeId
作为键,输出中需要的数组作为其值。如果该键尚不存在,请将该键添加[ typeId, Name, []]
为值。这样,第一项Name
将在输出中。这是 accumulator/ 的merged
样子:
{
"1": [1, "One", [{ "Name": "One" }, { "Name": "One Two" }]],
"2": [2, "Two", [{ "Name": "Two" }]],
"3": [3, "Three", [{ "Name": "Three" }, { "Name": "Three Two" }]]
}
然后使用,Object.values()
来获取这个对象的值作为一个数组
推荐阅读
- java - Redis部署到2个或更多容器时如何使用Redission清除Redis缓存?
- reactjs - 无法在 Visual Studio C# ASP 内的 React 应用程序上使用 Material-UI。NET 核心网络应用程序
- sql - SQL AWS Athena Group by 没有列
- swiftui - 我们如何强制 ForEach 使用 UUID 而不是 (id: \.self)?
- node.js - 测试具有依赖于另一个模式的验证的猫鼬模式
- amazon-web-services - 从 cloudformation 为 ALB 启用访问日志记录
- python - 一种将转换器应用于 pandas.read_sql 的方法?
- python - 尝试提取特定 API 响应数据时出现 KeyError
- php - 出于某种原因,当我将其添加到我的代码中时,我得到了意外的文件结束错误。但我无法弄清楚这段代码有什么问题
- javascript - 如何使用 Firebase Auth 作为 OIDC 向 Amplify GraphQL 发出经过身份验证的请求?