简体   繁体   中英

Object duplicates in JavaScript

My question is how can I pass from this :

const array = [
    {name: "Bline", score: 95},
    {name: "Flynn", score: 75},
    {name: "Carl", score: 80},
    {name: "Bline", score: 77},
    {name: "Flynn", score: 88},
    {name: "Carl", score: 80}
]

to this array of objects using javascript:

[
    {
      name: 'Bline',
      data: [95, 77]
    }
    {
      name: 'Flynn',
      data: [75, 88]
    }
    {
      name: 'Carl',
      data: [80, 80]
    }
    ]

I have tried using the duplicate but nothing so far

you should iterate over your array and set name as key and score as value in an array manner in an object :

let result = {}
for (let item of array) {
  if (!result[item.name]) result[item.name] = [item.score]
  else result[item.name].push(item.score)
}

You can get the expected result by first grouping the data with a reduce function.

let grouped = array.reduce(function (r, a) {
    r[a.name] = r[a.name] || [];
    r[a.name].push(a.score);
    return r;
}, {});

And then format it to what you wanted.

let formated = Object.entries(grouped).map(([key, value]) => {
    return {
        name : key,
        data: value
    }    
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM