javascript - 使用javascript将数组中的多个对象合并为一个基于一对的键值对
问题描述
我有一个基于网格过滤值的动态生成的数组,如下所示
[
{
attributeId: 145,
attributeName: "Status",
filterOperator: "Is equal to",
filterValue: "Active",
SortBy: ""
},
{
attributeId: 161,
attributeName: "Code",
filterOperator: "Contains",
filterValue: "22",
SortBy: ""
},
{
attributeId: 161,
attributeName: "Code",
filterOperator: "",
filterValue: "",
SortBy: "ASC"
}
]
这里生成了两个具有相同“attributeId”的对象,但一个对象具有 SortBy 详细信息,另一个具有过滤详细信息。现在我想将这两个对象合并为一个对象,这样它就会变得像
{
attributeId: 161,
attributeName: "Code",
filterOperator: "Contains",
filterValue: "22",
SortBy: "ASC"
}
如果对象是相同的,我可以使用删除重复项
this.columnList = Object.values(this.columnList.reduce((acc, cur) => Object.assign(acc, {
[cur.attributeName]: cur
}), {}));
这里 this.columnList 是数组名。这里有任何建议。谢谢。
解决方案
您可以reduce
基于attributeId
. 如果attributeId
累加器中已经存在,则循环遍历对象的条目,如果它不为空,则更新每个值。如果attributeId
不存在,将其添加到累加器
const input=[{attributeId:145,attributeName:"Status",filterOperator:"Is equal to",filterValue:"Active",SortBy:""},{attributeId:161,attributeName:"Code",filterOperator:"Contains",filterValue:"22",SortBy:""},{attributeId:161,attributeName:"Code",filterOperator:"",filterValue:"",SortBy:"ASC"}];
const merged = input.reduce((acc, o) => {
const { attributeId, ...rest } = o;
if (!acc[attributeId])
acc[attributeId] = { ...o }
else
{
Object.entries(rest).forEach(([k, v]) => {
if (v)
acc[attributeId][k] = v
})
}
return acc
}, {})
console.log(Object.values(merged))
推荐阅读
- javascript - 如何使用 jQuery 创建循环
- php - 如何从 Prestashop 1.7.6 中的表 stock_available 获取数量
- angular - 如何构建角度应用程序
- google-cloud-platform - 在 GCP 中将数据从 VM 实例传输到 BigQuery
- r - 如何在插入符号或 tidymodels 中使用 LASSO 进行嵌套交叉验证?
- r - 使用鼠标输入大型数据帧时出错
- c# - 为什么在通过 dotnet CLI 运行 ASP.NET Core 应用程序时看到项目目录名称而不是 dotnet(进程外)?
- flutter - AppBar内的后退按钮在颤动中显示黑屏
- javascript - JavaScript:垂直遍历多维数组
- python-3.x - 没有安装候选时如何将 libpcre3-dev 添加到 docker 映像 python3.8-slim