js array object list to object

Not much nonsense, let's start with an example, as follows:

mdata: [
    { a: 0.0, b: 0.0, c: 0.0, d: 0.0, e: 0.0, f: 0.0, g: 0.0 },
    { a: 1.0, b: 0.0, c: 0.0, d: 0.0, e: 0.0, f: 0.0, g: 0.0 },
    { a: 2.0, b: 0.0, c: 0.0, d: 0.0, e: 0.0, f: 0.0, g: 0.0 },
    { a: 3.0, b: 0.0, c: 0.0, d: 0.0, e: 0.0, f: 0.0, g: 0.0 },
    { a: 4.0, b: 0.0, c: 0.0, d: 0.0, e: 0.0, f: 0.0, g: 0.0 }
]

Convert the above code into object format, as follows: 

data: {
    a: [0, 1, 2, 3, 4],
    b: [0, 0, 0, 0, 0],
    c: [0, 0, 0, 0, 0],
    d: [0, 0, 0, 0, 0],
    e: [0, 0, 0, 0, 0],
    f: [0, 0, 0, 0, 0],
    g: [0, 0, 0, 0, 0]
}

accomplish: 

const newArr = this.mdata.reduce((obj, cur, index) => {
        Object.keys(cur).map((item) => {
          if (!obj[item]) {
            obj[item] = [cur[item]]
          } else {
            obj[item].push(cur[item])
          }
        })
        return obj
      }, {})
      console.log(newArr)

result:  

Guess you like

Origin blog.csdn.net/CSDN_33901573/article/details/126261902