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

How to get max value from a nested json

have json object of which I would like to get the max value of showstopinfo :

var data = [{
  "info": [
    {
      "ticketinfooo": {
        "showstopinfo": 1
      }
    },
    {
      "ticketinfooo": {
        "showstopinfo": 6
      }
    }

  ]
}, {

  "info": [
    {
      "ticketinfooo": {
        "showstopinfo": 22
      }
    },
    {
      "ticketinfooo": {
        "showstopinfo": 23
      }
    }

  ]
}]

I`ve just written the code below but it return NAN value:

var max = Math.max(...data.map(e => e.info.map(x => x.ticketinfooo.stoppinfoo.showstopinfo)))
console.log(max)

What is wrong with this code?

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

>Solution :

You need to map() on the outer array and also the inner info array. From there you’ll have a 2d array which you’ll need to flatten.

Here’s a working example:

var data = [{info:[{ticketinfooo:{showstopinfo:1}},{ticketinfooo:{showstopinfo:6}}]},{info:[{ticketinfooo:{showstopinfo:22}},{ticketinfooo:{showstopinfo:23}}]}];

var values = data.map(d => [...d.info.map(i => i.ticketinfooo.showstopinfo)]).flat();
var max = Math.max.apply(null, values);
console.log(max)
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