Search code examples
javascriptobjectgroup

How to group JavaScript Object in javascript


seek for help for grouping them. I got an input with this.

[
    {
        "apiName": "APISend",
        "channel": "Mozilla",
        "noa": 3
    },
    {
        "apiName": "API",
        "channel": "PostMan",
        "noa": 1
    },
    {
        "apiName": "APICall",
        "channel": "PostMan",
        "noa": 4
    },
    {
        "apiName": "API",
        "channel": "Mozilla",
        "noa": 2
    }
]

How can I group them as channel and then by apiName? My final output should be like this:

labels = ["Mozilla","PostMan"]

datasets = [{label:"APISend", data:[3,0]} , {label:"API",data:[2,1], {label:"APICall",data:[0,4]]}

Solution

  • just like this, you can have a try.

    const arr = [{'apiName': 'APISend', 'channel': 'Mozilla', 'noa': 3}, {'apiName': 'API', 'channel': 'PostMan', 'noa': 1}, {'apiName': 'APICall', 'channel': 'PostMan', 'noa': 4}, {'apiName': 'API', 'channel': 'Mozilla', 'noa': 2}]
    
    function transtArr(data){
      let labels = []
      let datasets = []
      data.forEach((value) => {
        labels.push(value.channel)
        let _indexNum = datasets.findIndex(x => x.label === value.apiName)
        if(_indexNum > -1){
          datasets[_indexNum].data.push(value.noa)
        } else {
          let _obj = {label: value.apiName, data: [value.noa]}
          datasets.push(_obj)
        }
      })
      return {labels: [...new Set(labels)], datasets}
    }