What is the best way to loop through unsorted JSON data and organize it into an array?

Currently, I am extracting data from an API in the form of a JSON object. The issue is that this JSON data is unordered by default. I am aware that JSON is meant to be unordered, but I would like to figure out how to loop through these keys and organize the data by storing them in an array. Currently, I have them displaying in a table using ng-repeat, but they appear in a random order. My ultimate goal is to have them sorted chronologically by date. Below is an example of the structure:

{
    "01/05/2016": {
         "Something1": {},
         "Something2": {}      
     },
    "01/01/2016": {
         "Something1": {},
         "Something2": {}      
     },
    "01/03/2016": {
         "Something1": {},
         "Something2": {}      
     }
}

 <tr ng-repeat="(key,value) in metrics_data">
          <td align="center">{{key}}</td>
          //and then I do another ng-repeat right here for values

Answer №1

It is important to note that orderBy does not support objects, so the first step is to convert the object into an array.

$scope.testObj = {
"01/05/2016": {
     "Thing1": {},
     "Thing2": {}      
 },
"01/01/2016": {
     "Thing1": {},
     "Thing2": {}      
 },
"01/03/2016": {
     "Thing1": {},
     "Thing2": {}      
 }
};

$scope.testObjArray = Object.keys($scope.testObj).map(
                     function(k) { 
                         return {date: k, details: $scope.testObj[k]} 
                     });

Once converted to an array, you can then use the orderBy filter.

ng-repeat="item in testObjArray | orderBy : 'date'"

For a live example, check out this link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attributes for MenuList in React Select

const { MenuList } = components; const CustomMenuList = ({ ...props }: any) => { console.log(props); return ( <div> <MenuList {...props} /> <hr className="m-0" /> <div className="tex ...

Mapbox struggling with performance because of an abundance of markers

I have successfully implemented a feature where interactive markers are added to the map and respond to clicks. However, I have noticed that the performance of the map is sluggish when dragging, resulting in a low frame rate. My setup involves using NextJ ...

Retrieve a JSON file from the local file system using AngularJS

I recently started learning AngularJS and I am trying to read a JSON file from my local system. However, when I attempt to do so, I encounter an exception error that says: "Access to restricted URI denied XMLHttpRequest." Here is the code snippet: var de ...

When the page reloads, the firebase currentUser variable is found to be

Currently utilizing Firebase for authentication. Prior to making a request to the backend, I always ensure to request the idToken. service.interceptors.request.use(async request => { const token = await firebase.auth().currentUser.getIdToken(); i ...

Check if there are any child nodes before executing the RemoveChild JavaScript function to avoid any errors

function delete(){ let k = document.getElementsByClassName('row'); for(let i=0; i<k.length; i++) { if(k[i].hasChildNodes()){ k[i].removeChild(k[i].childNodes[2]); } } } <div id="table"> <div class="row"& ...

Combining Objects in an Array using Node.js: A Step-by-Step Guide

I am working with Node.js and have 3 different sets of data. The first set contains: [ { "userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3", "dailyData":159392.235451, "dailyDataInUSC":255.28 ...

Attempting to integrate the Angular2 module text-mask-addon into the project

Currently, I am in the process of integrating text-mask-addons into my Angular application. You can find more information at https://github.com/text-mask/text-mask/tree/master/addons Despite attempting to follow the npm links suggestion, I am encountering ...

Is there a way to assign the scroll event context to `document.body` instead of `window`?

Discovery As I delved into the intricacies of web development, I stumbled upon a curious observation. In a particular MDN page, I noticed that the left and right sidebars had their scrollbars contained within themselves. However, the content block's ...

transmit information from a Node.js server to Ajax

Is it possible to verify if a user-entered token exists? Here is my Node.js controller: const checkToken = async (req, res) => { const token = req.body.token; User.findOne({'token': token}).then((user) => { if (user) { ...

Parsing dynamic keys and field names in JSON format

I am faced with a JSON string {"key": "2021-01-01 22:59:59", "data": {"field1": "newvalue1", "field2": "newvalue2"}} My task is to transform this JSON into the following structure: ...

Dependency injection of an Angular app factory toaster is causing the application to malfunction

I am currently working on an Angular application that utilizes Firebase as its backend. My goal is to inject 'toaster' as a dependency within my authorization app factory. Below is the initial setup of the app.factory: app.factory('principa ...

Issues encountered with integrating external jQuery/JavaScript functions with Wordpress child theme template

After creating a custom template in my WordPress child theme, I added a link to the Bootstrap v3.0.3 .js file stored on my site. While the popup modal is functioning properly, the jQuery tabs seem to be having some issues. Although they are being display ...

Eliminate item from array if it is found in JSON data

I have implemented a script to eliminate JSON objects from an array that exist in both the array itself and another JSON object: var stageChildren = stage.sprites; for (var i = 0; i < stageChildren.length; i++) { for (var x in mainMenu) { if ...

Using a for loop to add a nested div inside another div

Hey there, I've got a question about the loop that's currently in my code. Right now, I'm doing it manually and it seems to be working that way. $( '<div id="demo1" > <span class="value"></span> </div> ...

Verify the presence of the item within the array that is nested

I have the following JSON data const data = { rooms: [ { roomId: 1, schedules: [ { home1: "06:00", dayOfWeek: 1, away: "21:30" }, { home1: "06:05", dayOfWeek: 2, away: "22:30" } ...

Is it possible to execute this html-minifier through the terminal on Ubuntu?

I am encountering an issue while attempting to use this HTML minifier tool on Ubuntu via the command line. Every time I try to execute it, an error pops up. NodeJS and NPM installations go smoothly: root$ apt-get install -y nodejs npm Reading package lis ...

`How can I replace a link with text within a div using JavaScript or jQuery?`

I need help transforming the following HTML code: <div id="myText">Another hurricane is coming <a data-number="23">here</a>. And check out pictures <a data-number="43">here</a>.</div> into this: <div id="myText"> ...

What is the process for setting %20 to represent a space in URL parameters?

I am currently working on developing an android application that involves sending data to the server side using GPRS and SMS (via an SMS gateway). The challenge I am facing is with formatting the data before sending it to the SMS gateway. The format provid ...

Elevate the functionality of your table in BoostrapVue by customizing it to display items

How can I modify the code below to turn the items into input fields that the user must enter? Instead of listing the items, I would like to replace them with input fields. <template> <div> <b-form-input v-for="(item, index) in items" ...

jQuery script functions exclusively on the Firefox browser

After spending 2 weeks working hard on my first simple site/database, I've hit a roadblock. A friend helped me add jQuery, but now it only works in Mozilla and he has no idea why. I have very little knowledge of Java (and even less of PHP). Could some ...