[Solved] modify array of objects – javascript


Aggregation like this be handled by Array.reduce(). For example:

const arr = [
  {KEY1: "VALUE1", NAME: "VALUE2", PID: "VALUE36"},
  {KEY11: "VALUE1", NAME: "VALUE2", PID: "VALUE47"},
  {KEY11: "VALUE1", NAME: "VALUE4", PID: "VALUE49"},
  {KEY11: "VALUE1", NAME: "VALUE4", PID: "VALUE43"},
]

// Objects are basically associative arrays in JS, so...
// (For each item in arr, add or update an array at obj[item.NAME])
const obj = arr.reduce((obj, item) => {
  const val = [ item.PID ]
  obj[item.NAME] = Array.isArray(obj[item.NAME])
    ? obj[item.NAME].concat(val)
    : val
  return obj
}, {}) // start with obj = {}

/*
At this point, we have
obj = {
  "VALUE2": [
    "VALUE36",
    "VALUE47"
  ],
  "VALUE4": [
    "VALUE49",
    "VALUE43"
  ]
}
*/

// ...but since you specified separate objects, this finishes it off
const newArr = Object.entries(obj).map(([key, val]) => ({ [key]: val }))
console.log(newArr)

1

solved modify array of objects – javascript