首页 > 解决方案 > 使用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 是数组名。这里有任何建议。谢谢。

标签: javascriptarrays

解决方案


您可以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))


推荐阅读