Calculate max and average of JSON API result

  api, javascript, json

I have this JSON:

var myJSON = [
{
    "page": 1,
    "totalPages": 2,
    "data": [{
      "title": "Developer 1",
      "rating": 4.7
  }, {
      "title": "Developer 2",
      "rating": 7.8
  }]
}];

I need to calculate average and max rating.

From my perspective this should use map and reduce for this purpose, but, I’m not sure if the JSON has the right format, or if it needs any sanitization.

I’m using this code right now, but I get a weird string as an output:

var Max_JSO = myJSON.reduce( (acc, cur )=> ((acc.rating > cur.rating)? acc : cur) );
var Min_JSO = myJSON.reduce( (acc, cur )=> ((acc.rating < cur.rating)? acc : cur) );

var Avg_JSO = myJSON.reduce( (acc, cur, idx, arr )=> {
  let
    sum = acc.rating + cur.rating,
    no = idx +1;
  if (no === arr.length) { sum = sum / no };
  return { 'name': cur.name, 'rating': sum }
});

console.log ('max =', JSON.stringify(Max_JSO) );
console.log ('min =', JSON.stringify(Min_JSO) );

"max =", "{&quot;page&quot;:1,&quot;totalPages&quot;:5,&quot;data&quot;:[{&quot;title&quot;:&quot;Developer 1&quot;,&quot;rating&quot;:4.7},{&quot;title&quot;:&quot;Developer 2&quot;,&quot;rating&quot;:7.8}]}"
"min =", "{&quot;page&quot;:1,&quot;totalPages&quot;:5,&quot;data&quot;:[{&quot;title&quot;:&quot;Developer 1&quot;,&quot;rating&quot;:4.7},{&quot;title&quot;:&quot;Developer 2&quot;,&quot;rating&quot;:7.8}]}"

Is there any way to do this better?

Also, I need to not only read rating from data key, but also outside of it, as you can see on var myJSON

Like produce a resulting json like this:

  {
      "Developer 1": 4.7,
      "Developer 2": 7.8,
  }

MIN being Developer 1 and MAX Developer 2

Source: Ask Javascript Questions

LEAVE A COMMENT