Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS creating new object array using another object

I have below object array

var testdata = [{
                 TYPE: 'type 1', Category: 'Booking', Count : 5
               },
               {
                 TYPE: 'type 2', Category: 'Booking', Count : 15
               },
               {
                 TYPE: 'type 1', Category: 'Planning', Count : 10
               },
               {
                 TYPE: 'type 3', Category: 'SALES', Count : 5
               }]

I want to group each category and then by type and count as below:

 var resultdata =
    {
     "Booking": {
       "type 1": 5,
       "type 2": 15
     },
    "Planning": {
       "type 1": 10
     },
    "SALES": {
       "type 3": 5
     },
    }

so far I have written bellow logic but it fails to give me expected result it is only adding the last values of each category

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 $.each(testdata , function (key, value) {
            if(value.Category == "Booking"){
                bookingarray['Booking'] = {[value.TYPE]: value.Count}
            }            
         })

>Solution :

You could try something like this:

$.each(testdata, function(key, value) {
  if (!bookingarray[value.Category]) {
    bookingarray[value.Category] = {} // if example "Booking" does not exist in resultData, then create it
  }
  bookingarray[value.Category][value.TYPE] = value.Count
})

Demo

var testdata = [{
    TYPE: 'type 1',
    Category: 'Booking',
    Count: 5
  },
  {
    TYPE: 'type 2',
    Category: 'Booking',
    Count: 15
  },
  {
    TYPE: 'type 1',
    Category: 'Planning',
    Count: 10
  },
  {
    TYPE: 'type 3',
    Category: 'SALES',
    Count: 5
  }
]

var bookingarray = {};

$.each(testdata, function(key, value) {
  if (!bookingarray[value.Category]) {
    bookingarray[value.Category] = {}
  }
  bookingarray[value.Category][value.TYPE] = value.Count
})

console.log(bookingarray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading