Arrange the JSON object according to the date value

I am working on a JavaScript project that involves objects.

Object {HIDDEN ID: "06/03/2014", HIDDEN ID: "21/01/2014"}

My goal is to create a new object where the dates are sorted in descending order.

Here's an example of what I want:

SortedObject {"HIDDEN ID" : "21/01/2014", "HIDDEN ID" : "06/03/2014"}

I have knowledge of how to achieve this with an array, but I'm facing challenges iterating through objects to sort by date.

Any assistance would be greatly appreciated.

UPDATE:

This is my current code snippet.

for(var x=0; x<folderList.length; x++){
                    retrieveAllFilesInFolder(folderList[x], function(){
                        var arr = []; 
                        for(var i in fileListObj) { 
                           var d = fileListObj[i].split("/");
                           arr.push({"id": i, "date":(new Date(d[2],d[1]-1,d[0]))}); 
                        }
                        arr.sort(function(a,b) { return a.date < b.date;});
                        console.log(arr); 
                    });
                }

However, the output is not sorted by date as intended.

Object 1 id: "hiddenID1", date: Mon Nov 18 2013 00:00:00 GMT+0000 (GMT Standard Time)
Object 2 id: "hiddenId2", date: Thu Mar 06 2014 00:00:00 GMT+0000 (GMT Standard Time)
Object 3 id: "hiddenId3", date: Thu Sep 05 2013 00:00:00 GMT+0100 (GMT Daylight Time)

Answer №1

Sorting an object can be tricky because it contains key value pairs, not serialized items.

To sort an object, you first need to create an array and then sort that array accordingly.

var obj = {"a" : "21/01/2014", "b" : "06/03/2014"};

var arr = []; 

for(var i in obj) { 

   var d = obj[i].split("/"); 

   arr.push({"id": i, "date":(new Date(d[2],d[1]-1,d[0]))}); 
}

arr.sort(function(a,b) { return a.date.valueOf() > b.date.valueOf();});

After sorting, the result will be an array arr organized by date.

Answer №2

In dealing with JSON objects, sorting them directly is not possible. One workaround is to extract the values into an array and then sort that array instead. It seems like the two "hidden id" identifiers are separate fields, as the provided example does not adhere to proper JSON format.

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

Learn how to import MarkerClusterer from the React Google Maps library without using the require method

The sample provided utilizes const { MarkerClusterer } = require("react-google-maps/lib/components/addons/MarkerClusterer");, however, I would prefer to use the import method. I attempted using: import { MarkerClusterer } from 'react-google-maps/lib ...

Utilize .map function to format a date string and generate a table

I am currently utilizing .map along with React in order to generate a table using a coupons object. My goal is to format a date string into the "mm/dd/yyyy" format, with coupon.starts_at typically being set as coupon.starts_at = "2013-08-03T02:00:00Z" I h ...

Creating custom generic functions such as IsAny and IsUnknown that are based on a table of type assignability to determine

I attempted to craft a generic called IsAny based on this resource. The IsAny generic appears to be functioning correctly. However, when I implement it within another generic (IsUnknown), it fails: const testIsUnknown2: IsUnknown<any> = true; // iss ...

Please refrain from refreshing the page multiple times in order to receive updated data from the database

Currently, I have created a countdown timer from 00:60 to 00:00. However, once the timer reaches 00:00, I am looking to refresh the page only once in order to retrieve a new value from the database. Does anyone have any suggestions on how to achieve this ...

Validating alpha-numeric passwords with JavaScript

I created a JavaScript function to validate if a password is alphanumeric. However, I am facing an issue where the alert message is not being displayed when the password is not alphanumeric. Below is my code snippet: if (!input_string.match(/^[0-9a-z]+$ ...

The initial attempt at using Ajax inside onbeforeunload is unsuccessful

I have attempted to attach the beforeunload event by executing the subsequent script in order to use AJAX to navigate to a specific URL. However, I am encountering an issue where AJAX does not work the first time when I refresh the page, as the URL is no ...

Monitor and adjust variables simultaneously using AngularJS

My goal is to dynamically calculate and display values based on two other variables in real time. I've successfully managed to track one variable, but not both simultaneously. $scope.color_slider_bar = { value:0, minValue: 0, maxValue: ...

Ext.js Ext.grid.Panel with advanced filtering capabilities

I encountered an issue with the following code snippet... Ext.define("Requestor.view.main.RequestGrid", { extend: 'Ext.grid.Panel', // Our base class. A grid panel. ... extensive code ... columns: [ ... additional code ... { ...

The server's request is being processed through jQuery's ajax functionality

Recently, I've started working with jQuery and AJAX. Essentially, the webpage sends an HTTP post request, and the server-side DLL responds by writing a JSON-formatted response back to the page. I'm trying to understand how to handle this response ...

Sending JavaScript variables to an external CSS file

I've been searching for a solution without much luck. I must admit, my CSS skills are pretty basic. Currently, I am using Muxy.io to manage notifications for my livestreams. The platform allows customization of notifications through HTML and CSS file ...

What is the best method to convert a standard PHP array into a JSON array while preserving the indexes?

Imagine starting with a basic array. <?php $a = array('a','b','c'); ?> Is there a way to create a JSON array as shown below? { '0':'a', '1':'b', '2':'c' } T ...

Checking for the status of a checked box when the ::after pseudo-element is added after the box is marked

I need help verifying if a checkbox is checked in my selenium code. After the checkbox is checked, it adds ::after but I'm struggling to confirm the existence of that pseudo element. Can anyone assist me in resolving this issue? I have been unable to ...

Retrieve all items from the firebase database

I have a query. Can we fetch all items from a particular node using a Firebase cloud function with an HTTP Trigger? Essentially, calling this function would retrieve all objects, similar to a "GET All" operation. My next question is: I am aware of the onW ...

Add middleware to one individual store

When working with Redux, it is possible to create middleware that can be easily applied to the entire store. For example, I have a middleware function called socketMiddleware that connects to a socket and dispatches an action when connected. function sock ...

Creating an interactive API endpoint in AngularJS for a DreamFactory stored procedure just got easier with these simple steps

If I am using a factory/service to access my API in DreamFactory. FoundationApp.factory('testAPI', function($resource, ChildID) { return $resource('http://Domain.com/rest/RemoteDB/_proc/TimeLog_Checkin(:ChildID)/?app_name=App&fields ...

The use of $scope.$destroy may resolve memory leak issues, but it can also cause

In my TypeScript AngularJS application, I have a child directive that is dynamically generated. The template and controller are assigned at runtime based on the requirements of the situation, with multiple directives within the template. To display multipl ...

Exploring ways to create simulated content overflow using react-testing-library

I have integrated material-table with material ui to develop a spreadsheet application. One of the features I have added is setting a maximum width of 50px for cells. If the content in a cell exceeds this width, it will display an ellipsis at the end of ...

Is there a way to showcase the JSON data within a nested array using VueJS?

Here is my Vue.js code: <script> new Vue({ el: '#feed' , data: { data: [], }, mounted() { this.$nextTick(function() { var self = this; var id = window.location.href.split('=').pop(); ...

Collaborating and passing on a MongoDB connection to different JavaScript files

I am currently working with Node.js/Express.js/Monk.js and attempting to share my MongoDB connection across multiple JS files. Within apps.js, I have set up the following: var mongo = require('mongodb'); var monk = require('monk'); va ...

Do you know of any helpful resources for learning JSON with PHP through video tutorials?

I've been browsing the internet trying to learn about JSON, but a lot of tutorials are just too complicated for me. I'm specifically interested in learning how to use JSON with jQuery and PHP. If anyone has any recommendations for videos or websi ...