How to order json in javascript

How to order below json by Location , Name ="Total" comes before detail

{
   "records":[
      {
         "Location":"UK",
         "RecordType":"Fruits",
         "Qty":16,
         "Name":"Total"
      },
      {
         "Location":"UK",
         "RecordType":"Grocery",
         "Qty":11,
         "Name":"Total"
      },
      {
         "Location":"US",
         "RecordType":"Fruits",
         "Qty":5,
         "Name":"Total"
      },
        {
         "Location":"US",
         "RecordType":"Grocery",
         "Qty":17,
         "Name":"Total"
      },
      {
         "Location":"US",
         "RecordType":"Fruits",
         "Productid":123,
         "Qty":5,
         "Name":"Apple"
      },
      {
         "Location":"UK",
         "RecordType":"Fruits",
         "Productid":124,
         "Qty":11,
         "Name":"Bananna"
      },

      {
         "Location":"US",
         "RecordType":"Grocery",
         "Productid":223,
         "Qty":6,
         "Name":"Rice"
      },
      {
         "Location":"UK",
         "RecordType":"Grocery",
         "Productid":224,
         "Qty":11,
         "Name":"Beans"
      }
   ]
}

Open in new window




How to rearrange json so Location + Total comes before detail

{
   "records":[
      {
         "Location":"UK",
         "RecordType":"Fruits",
         "Qty":16,
         "Name":"Total"
      },
      {
         "Location":"UK",
         "RecordType":"Fruits",
         "Productid":124,
         "Qty":11,
         "Name":"Bananna"
      },
      {
         "Location":"UK",
         "RecordType":"Grocery",
         "Qty":11,
         "Name":"Total"
      },
      {
         "Location":"UK",
         "RecordType":"Grocery",
         "Productid":224,
         "Qty":11,
         "Name":"Beans"
      },
      {
         "Location":"US",
         "RecordType":"Fruits",
         "Qty":5,
         "Name":"Total"
      },
      {
         "Location":"US",
         "RecordType":"Fruits",
         "Productid":123,
         "Qty":5,
         "Name":"Apple"
      },
        {
         "Location":"US",
         "RecordType":"Grocery",
         "Qty":17,
         "Name":"Total"
      },
      {
         "Location":"US",
         "RecordType":"Grocery",
         "Productid":223,
         "Qty":6,
         "Name":"Rice"
      }
   ]
}

Open in new window

Bharat GuruAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ste5anSenior DeveloperCommented:
By changing the order in your object.

But you're aware that order is absolutly meaningless in this context?
Bharat GuruAuthor Commented:
But some times in json total comes before detail and I want to put total always first
Bharat GuruAuthor Commented:
Some times detail comes before total and
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Bernard S.CTOCommented:
Ste5an pointed that the order is probably meaning less, especially if the json is read by another program somewhere///
Bharat GuruAuthor Commented:
In json some time the order is as below and I want to generate the table using javascript where total comes before detail.
{
    "records":[
  {
          "Location":"UK",
          "RecordType":"Fruits",
          "Productid":124,
          "Qty":11,
          "Name":"Bananna"
       },
     {
          "Location":"UK",
          "RecordType":"Fruits",
          "Productid":124,
          "Qty":11,
          "Name":"Bananna"
       },
            {
          "Location":"UK",
          "RecordType":"Fruits",
          "Productid":230
          "Qty":25
          "Name":"Peach
       },
            {
          "Location":"UK",
          "RecordType":"Grocery",
          "Productid":224,
          "Qty":11,
          "Name":"Basmati Rice"
       },
       {
          "Location":"UK",
          "RecordType":"Fruits",
          "Qty":16,
          "Name":"Total"
       },
       {
          "Location":"UK",
          "RecordType":"Grocery",
          "Qty":11,
          "Name":"Total"
       }
        ]
 }


Table should as below
Location, RecordType, Qty, Name
UK,  Fruits, Total , qty
UK,  Fruits, products , qty
UK,  Fruits, products , qty
UK,  Fruits, products , qty
...
UK,  Grocery, Total , qty
UK,  Grocery, products , qty
UK,  Grocery, products , qty
UK,  Grocery, products , qty
..
UK,  GroceryType2, Total , qty
UK,  GroceryType2, products , qty
UK,  GroceryType2, products , qty
UK,  GroceryType2, products , qty
..
Bernard S.CTOCommented:
Your table is going to be displayed by some program.
As far as I understand, you currently read  each object and display it asap.

You might consider silghtly alterating you program so that it keeps all objetcs / lines until they are all read, and then display them in the order you want.

You did not mention which program is generating the output. Is it a javascript program to whch you have access?
Bharat GuruAuthor Commented:
yes my json string is in javascript
ste5anSenior DeveloperCommented:
In json some time the order is as below and I want to generate the table using javascript where total comes before detail.
Then just sort the data before creating/displaying your table.
Slick812Commented:
hello, , The JSON data set looks like a warehouse database output for food that's taken out of the warehouse, these record lists are usually long with hundreds of different product items, which may require a different approach than I use here for only TWO product types Grocery and Fruits?

here is my web page and javascript to read and sort a JSON data set of an array of products and totals, then show these records in a web <table> -

<!DOCTYPE html>
<html lang="en"><head>
<title>Jason Array reorded to table</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
<style>
body{height:100%; background: #e3f7ff;}

#dft {background: #dfe;
display: inline-block;
border:1px solid #7b6;
padding: 7px;
margin: 7px;}

#dft thead {background: #fff; 
color: #888;}

#dft th {border:2px solid #aaa;
padding: 4px;
text-align:center;}

#dft td {border:1px solid #000;
padding: 4px;
text-align:center;}

</style>
</head><body>
<h3>Jason Array reorded to table</h3>
<div id="dft"></div>
<hr>
the end

<script>
   
var wrl = {
   action:"query",
   Warehouse:"NJ",
   records:[
      {
         Location:"UK",
         RecordType:"Fruits",
         Qty:22,
         Name:"Total"
      },
     {
          Location:"UK",
          RecordType:"Fruits",
          Productid:321,
          Qty:11,
          Name:"Apple"
       },
      {
         Location:"UK",
         RecordType:"Grocery",
         Qty:7,
         Name:"Total"
      },
      {
         Location:"US",
         RecordType:"Fruits",
         Qty:17,
         Name:"Total"
      },
        {
         Location:"US",
         RecordType:"Grocery",
         Qty:9,
         Name:"Total"
      },
      {
         Location:"US",
         RecordType:"Fruits",
         Productid:384,
         Qty:7,
         Name:"Bananna"
      },
      {
         Location:"US",
         RecordType:"Fruits",
         Productid:123,
         Qty:5,
         Name:"Apple"
      },
      {
         Location:"UK",
         RecordType:"Fruits",
         Productid:124,
         Qty:11,
         Name:"Bananna"
      },

      {
         Location:"US",
         RecordType:"Grocery",
         Productid:472,
         Qty:6,
         Name:"Rice"
      },
      {
         Location:"UK",
         RecordType:"Grocery",
         Productid:724,
         Qty:7,
         Name:"Beans"
      },
            {
          Location:"US",
          RecordType:"Fruits",
          Productid:230,
          Qty:5,
          Name:"Peach"
       },

      {
         Location:"US",
         RecordType:"Grocery",
         Productid:223,
         Qty:3,
         Name:"Bread"
      }
   ]
}

var outStr = ["<table><thead><tr><th>Location</th><th>RecordType</th>"+
    "<th>Name</th><th>ProductID</th><th>Qty</th><tr></thead><tbody>",
    ["",""],["",""],"</tbody></table>"],
  tempStr = "",sc= "<tr><td columnspan='5' style='border:0'>&nbsp;</td></tr>";
    
function sortRecords(country, record) {
var pids = record.Productid ? record.Productid : '-';
tempStr = "<tr><td>"+record.Location+"</td><td>"+record.RecordType+
      "</td><td>"+record.Name+"</td><td>"+pids+
      "</td><td>"+record.Qty+"</td></tr>";

switch(record.RecordType) {
    case "Grocery":
      if (record.Name == "Total") outStr[country][0] = tempStr + outStr[country][0];
      else
      outStr[country][0] += tempStr;
        break;
    case "Fruits":
      if (record.Name == "Total") outStr[country][1] = tempStr + outStr[country][1];
      else
      outStr[country][1] += tempStr;
        break;
    default:
      outStr[country][0] = "ERROR - "+record.RecordType;
  } 
}
    
for(var i=0;i<wrl.records.length;i++) {
  if (wrl.records[i].Location == "US") {
    sortRecords(1, wrl.records[i]);
    }
     else if (wrl.records[i].Location == "UK") {
     sortRecords(2, wrl.records[i]);
    }
  }

  document.getElementById("dft").innerHTML = outStr[0]+outStr[1][0]+sc+outStr[1][1]+sc+outStr[2][0]+sc+outStr[2][1]+outStr[3];
</script>

</body></html>

Open in new window

this works for me in firefox

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ste5anSenior DeveloperCommented:
I'm still not sure, what your asking. But what's wrong with sorting your data??

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Jason Array reorded to table</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
  <style>
    body { height: 100%; background: #e3f7ff; }
    #dft { background: #dfe; display: inline-block; border: 1px solid #7b6; padding: 7px; margin: 7px; }
    #dft thead { background: #fff; color: #888; }
    #dft th { border: 2px solid #aaa; padding: 4px; text-align: center; }
    #dft td { border: 1px solid #000; padding: 4px; text-align: center; }
    td.empty { border: 0; height: 1em; }    
  </style>
  <script>
    function MockAjaxResult() {
      return `{
            "records": [
                { "Location": "UK", "RecordType": "Fruits", "Qty": 16, "Name": "Total" },
                { "Location": "UK", "RecordType": "Fruits",  "Productid": 124, "Qty": 11, "Name": "Bananna" },
                { "Location": "UK", "RecordType": "Grocery", "Qty": 11, "Name": "Total" },
                { "Location": "UK", "RecordType": "Grocery", "Productid": 224, "Qty": 11, "Name": "Beans" },
                { "Location": "US", "RecordType": "Fruits", "Qty": 5, "Name": "Total" },
                { "Location": "US", "RecordType": "Fruits", "Productid": 123, "Qty": 5, "Name": "Apple" },
                { "Location": "US", "RecordType": "Grocery", "Qty": 17, "Name": "Total" },
                { "Location": "US", "RecordType": "Grocery", "Productid": 223, "Qty": 6, "Name": "Rice" }
            ]
        }`;
    }

    function AppendRecords(records) {
      var sortedRecords = SortRecords(records);
      var lastLocation = undefined, lastRecordType = undefined;
      var table = document.getElementById("output");
      for (var count = 0; count < sortedRecords.length; count++) {
        var normalRecord = lastLocation === undefined && lastRecordType === undefined ||
          sortedRecords[count].Location === lastLocation && sortedRecords[count].RecordType === lastRecordType;
        if (normalRecord) {
          AddRecord(table, sortedRecords[count]);
        }
        else {
          AddRecord(table);
          AddRecord(table, sortedRecords[count]);
        }

        lastLocation = sortedRecords[count].Location;
        lastRecordType = sortedRecords[count].RecordType;
      }
    }

    function AddRecord(table, record) {
      var row = table.insertRow(table.rows.length);
      if (record != undefined) {
        row.insertCell(0).appendChild(document.createTextNode(record.Location));
        row.insertCell(1).appendChild(document.createTextNode(record.RecordType));
        row.insertCell(2).appendChild(document.createTextNode(record.Name));
        row.insertCell(3).appendChild(document.createTextNode(record.Productid));
        row.insertCell(4).appendChild(document.createTextNode(record.Qty));
      } else {
        var cell = row.insertCell(0);
        cell.colSpan = 5;
        cell.classList.add('empty');
      }
    }

    function SortRecords(records) {
      var SORT_MAGIC = '\\u0xE0000';
      return records.sort(function (a, b) {
        if (a.Location + a.RecordType + a.Name.replace('Total', SORT_MAGIC) < b.Location + b.RecordType + b.Name.replace('Total', SORT_MAGIC))
          return -1;
        if (a.Location + a.RecordType + a.Name.replace('Total', SORT_MAGIC) > b.Location + b.RecordType + b.Name.replace('Total', SORT_MAGIC))
          return 1;
        return 0;
      });
    }

    window.onload = function () {
      var json = JSON.parse(MockAjaxResult());
      AppendRecords(json.records);
    }
  </script>
</head>

<body>
  <h3>Jason Array reorded to table</h3>
  <div id="dft">
    <table id="output">
      <thead>
        <tr>
          <th>Location</th>
          <th>RecordType</th>
          <th>Name</th>
          <th>ProductID</th>
          <th>Qty</th>
          <tr>
      </thead>
      <tbody>
      </tbody>
    </table>

  </div>
  <hr> the end
</body>

</html>

Open in new window


Depending on SORT_MAGIC being a string greater as all names or lesser than all names, the sort order of the Name property sorts 'Total' to the end or the beginning of a group.
Bharat GuruAuthor Commented:
Thanks
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.