首页 > 解决方案 > 转换对象中具有相同键的数组

问题描述

我有一个数组,我想将其转换为按相同键分组的对象(这只是一个数字)

let array = [

   {"2": {
       "5": {
         "valore": "COLORE 1",
         "obbligatorio": null
        }
     }
   },
    {"2": {
       "20": {
         "valore": "MATERIALE 2",
          "obbligatorio": true
      }
    }
   },
   {"2": {
        "21": {
           "valore": "LUNGHEZZA 2",
            "obbligatorio": true
        }
   }},
  {"3": {"6": {"valore": "MATERIALE 4","obbligatorio": true}}}]

我的目的是在对象中转换数组并按相同的键进行分组,如下所示:

"2": {
  "5": {
    "valore": "COLORE 1",
    "obbligatorio": null
  },
  "20": {
    "valore": "LUNGHEZZA 2",
    "obbligatorio": true
  },
  "21": {
    "valore": "MATERIALE 3",
    "obbligatorio": true
  }
},
"3": {
  "6": {
    "valore": "MATERIALE 4",
    "obbligatorio": true
  }
}

问题是当我尝试转换时:

let obj = Object.assign({}, ...array);

它仅按两个值分组:

"2": {最后一个值} "3": {3的值}

我该如何解决这种行为?

标签: typescriptobject

解决方案


let array = [{
    "2": {
      "5": {
        "valore": "COLORE 1",
        "obbligatorio": null
      }
    }
  },
  {
    "2": {
      "20": {
        "valore": "MATERIALE 2",
        "obbligatorio": true
      }
    }
  },
  {
    "2": {
      "21": {
        "valore": "LUNGHEZZA 2",
        "obbligatorio": true
      }
    }
  },
  {
    "3": {
      "6": {
        "valore": "MATERIALE 4",
        "obbligatorio": true
      }
    }
  }
]

const output = array.reduce((acc, val) => {
  const key = Object.keys(val)[0]
  if (!acc[key]) acc[key] = {}
  acc[key] = { ...acc[key], ...val[key]}
  return acc
}, {})

console.log(output)


推荐阅读