Tips on organizing JSON data with JavaScript

After receiving my $http response, the data is presented in the format below:

$scope.rooms = {  
    '2B' : [    
        {"RoomEmailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ebd9a9c6d8d9d8ab868ec5888486">[email protected]</a>","RoomName":"2B-323"},    
        {"RoomEmailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ccfe8ee1fdfeff8ca1a9e2afa3a1">[email protected]</a>","RoomName":"2B-123"}     
    ],   
    '5A' : [  
        {"RoomEmailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86b3c7abb5b4b5c6ebe3a8e5e9eb">[email protected]</a>","RoomName":"5A-323"},   
        {"RoomEmailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="754034584447463518105b161a18">[email protected]</a>","RoomName":"5A-123"},  
        {"RoomEmailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f1c4b0dcc5c3c2b19c94df929e9c">[email protected]</a>","RoomName":"5A-423"}  
    ],  
    '1A' : [  
        {"RoomEmailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9faedeb2acadacdff2fab1fcf0f2">[email protected]</a>","RoomName":"1A-323"},  
        {"RoomEmailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dbea9af6eae9e89bb6bef5b8b4b6">[email protected]</a>","RoomName":"1A-123"},  
        {"RoomEmailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a796e68a939594e7cac289c4c8ca">[email protected]</a>","RoomName":"1A-423"}  
    ]  
}

To arrange this data in a specific order as shown below:

$scope.rooms = {  
    '1A' : [  
        {"RoomEmailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d3c4c203c3f3e4d6068236e6260">[email protected]</a>","RoomName":"1A-123"},  
        {"RoomEmailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a7b0b677978790a272f64292527">[email protected]</a>","RoomName":"1A-323"},  
        {"RoomEmailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="deef9ff3eaeced9eb3bbf0bdb1b3">[email protected]</a>","RoomName":"1A-423"}  
    ],  
    '2B' : [  
        {"RoomEmailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ab99e9869a9998ebc6ce85c8c4c6">[email protected]</a>","RoomName":"2B-123"},  
        {"RoomEmailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c8fa8ae5fbfafb88a5ade6aba7a5">[email protected]</a>","RoomName":"2B-323"}       
    ],  
    '5A' : [  
        {"RoomEmailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a194e08c909392e1ccc48fc2cecc">[email protected]</a>","RoomName":"5A-123"},  
        {"RoomEmailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aa9feb87999899eac7cf84c9c5c7">[email protected]</a>","RoomName":"5A-323"},        
        {"RoomEmailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="380d79150c0a0b78555d165b5755">[email protected]</a>","RoomName":"5A-423"}              
    ],  
}

I am looking for guidance on how to implement this sorting using JavaScript.

Answer №1

It appears that you have rearranged the keys within the object. Keep in mind that object key-values cannot be sorted; they need to be placed in an array for sorting to take place. To sort the arrays that serve as values of those keys, you can utilize the reduce method to create a new object without mutating the original rooms object.

const result = Object.keys(rooms).reduce((obj, roomKey) => {
  obj[roomKey] = rooms[roomKey].slice().sort((a, b) => a.RoomName > b.RoomName);
  return obj;
}, {});

See it in action here: http://jsbin.com/paqavaxako/edit?html,js,console

Answer №2

Is this what you're looking for? Use the delete function to reassign values to the object instead. Here is how you can use it:

sort(rooms, by("RoomName", "RoomEmailId"))

Custom Code

function by(columns) {
    columns = typeof columns == "string" ? columns.split(",") : columns;

    function compare(a, b) {
        return a > b ? 1 : a < b ? -1 : 0;
    }

    return function (a, b) {
        for (var i in columns) {
            var p = columns[i];
            var it = compare(a[p], b[p]);
            if (it) {
                return it;
            }
        }
        return 0;
    }
}

function sort(o, comparator) {
    return Object.keys(o).sort().reduce(function (o, key) {
        var it = o[key];
        delete o[key];
        o[key] = it.sort ? it.sort(comparator) : it;
        return o;
    }, o);
}

Testing Functions

test("Sorting Keys", () => {
    let o = {b: 2, a: 1};

    expect(Object.keys(o)).toEqual(["b", "a"]);
    expect(sort(o, null)).toEqual({a: 1, b: 2});
    expect(Object.keys(o)).toEqual(["a", "b"]);
});

test("Sorting Values", () => {
    let o = {b: [{value: 2}, {value: 1}], a: [{value: 4}, {value: 3}]};

    expect(Object.keys(o)).toEqual(["b", "a"]);
    expect(sort(o, by("value"))).toEqual({b: [{value: 1}, {value: 2}], a: [{value: 3}, {value: 4}]});
    expect(Object.keys(o)).toEqual(["a", "b"]);
});

Demonstration

var rooms = {  
    '2B' : [    
        {"RoomEmailId":"example1","RoomName":"2B-323"},    
        {"RoomEmailId":"example2","RoomName":"2B-123"}     
    ],   
    '5A' : [  
        {"RoomEmailId":"example3","RoomName":"5A-323"},   
        {"RoomEmailId":"example4","RoomName":"5A-123"},  
        {"RoomEmailId":"example5","RoomName":"5A-423"}  
    ],  
    '1A' : [  
        {"RoomEmailId":"example6","RoomName":"1A-323"},  
        {"RoomEmailId":"example7","RoomName":"1A-123"},  
        {"RoomEmailId":"example8","RoomName":"1A-423"}  
    ]  
};
function by(columns) {
    columns = typeof columns == "string" ? columns.split(",") : columns;

    function compare(a, b) {
        return a > b ? 1 : a < b ? -1 : 0;
    }

    return function (a, b) {
        for (var i in columns) {
            var p = columns[i];
            var it = compare(a[p], b[p]);
            if (it) {
                return it;
            }
        }
        return 0;
    }
}

function sort(o, comparator) {
    return Object.keys(o).sort().reduce(function (o, key) {
        var it = o[key];
        delete o[key];
        o[key] = it.sort ? it.sort(comparator) : it;
        return o;
    }, o);
}
console.log("Unsorted Rooms:", rooms);
console.log("Sorted Rooms:", sort(rooms, by("RoomName", "RoomEmailId")));

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

How can I retrieve the Azure subscription IDs of the currently logged in user using @azure/msal-angular?

I successfully authenticated a user using @azure/msal-angular and received the id_Token, access_Token and tenant Id. Now I am looking to retrieve the logged in user's azure subscriptions. Is there a way to achieve this through msal or are there any Ja ...

How can you transform the outcome of a TYPO3 repository search into a JSON format?

Is it possible to convert the outcome of a "findAll()" function on a Repository into a JSON object, make changes to specific properties in JavaScript, and then send it back to the Action, converting it again for use by the Action to persist it in the datab ...

Dealing with JSON post requests in Node.js using Express 4

Attempting to develop a basic Express application that accepts JSON through a Post request. The current server-side code is as follows: var express = require('express'); var bodyParser = require('body-parser'); var app = express(); ap ...

What is the best way to retrieve a particular variable from an ng-repeat loop?

I'm currently working on a task where I have an ng-repeat loop that generates multiple dropdowns. Each dropdown is associated with a unique ID generated by the controller for reference purposes. The issue I am facing is that when a user selects an op ...

What is the best way to trigger a function in Vue.js when a click event occurs on Google Maps?

In my Nuxt.js app in SPA mode, I am utilizing the Google Maps API and I'm aiming to trigger a function in Vue.js methods from the gmap click event. When attempting this.createInfoWindow(), it became apparent that this does not refer to the VueCompone ...

Is it possible to switch the background image when hovering?

Is the image proportion relevant to the issue at hand? <style> .img1:hover { background-image: url({%static 'images/img2.gif' %}); -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; backg ...

tips for building angularjs widgets with limited scope

Is there a way to generate widgets from HTML scripts on a webpage? For example: <script type="text/html" id="widget-simple"> <div class="widget-simple"> This is my widget and its name is {{ test }} </div> </script> & ...

The term 'ItemIsLoading' is typically used as a type, however, it is being incorrectly used as a value in this context

Currently, I am in the process of developing a typescripted Redux store for a react project. While the Interfaces are functioning correctly, I encountered an error when attempting to pass them within the exports themselves. The error message states "' ...

Techniques for accessing and modifying JSON data with AngularJs

I am new to AngularJS and I am struggling with retrieving and updating values using JSON. I have attempted to access data from a JSON file, but unfortunately, it is not working. Here is the code snippet I have been using: { $http.get(& ...

What is the method to make Celery return a JSON object instead of bytea?

I am new to working with Celery in Python 3 and I decided to start by returning a string "this was a hello task" as a result from a worker and storing it in a Postgres database. However, when I retrieve the result from the database, it appears as a memoryv ...

Changes made to one order's information can impact the information of another order

Currently, I am in the process of developing a unique shopping cart feature where users input a number and a corresponding product is added to a display list. Users have the ability to adjust both the price and quantity of the products, with the total pric ...

Choose a Date from the Calendar and Modify the Link Text

I have a Link Label on my page that triggers a calendar pop-up when clicked. I want the label to update to the selected date in the format '30 JAN 2017' from the calendar. The issue lies with the local variable var dateText =...; although the la ...

Nodejs is utilized to alter the data format as it is transferred from the client to the server

I'm encountering an issue with transmitting my data to the server using Node.js. I have a feeling that there are discussions on this topic already, but I'm unsure of what to search for to locate them... Here's a brief overview of my applica ...

Having trouble getting the json2html Python library to function correctly

I am attempting to generate a new JSON file with custom input, converting the JSON data into HTML format, and then saving it as a .html file. However, I am encountering an error during the process of creating both the JSON and HTML files. Below is the code ...

Modify CSS class if the window size is smaller than specified value

Is there a way to modify the attributes of a CSS class if the browser window is less than 600px in height? The current default properties are as follows: .side { height:400px; width:700px; } I am looking to update it to: .side { height:300px; width:550p ...

Exploring how arrays are managed in Excel with the SUMPRODUCT() function

There are three arrays labeled A, B, and C where A - B = C. In excel, these arrays are organized in columns as follows: A, B, C, A, B, C, A, B, C... D, E The objective is to calculate the sum of all values in C that are greater than 0 (D) and all values ...

What steps can be taken to identify the referrer of external links when the target attribute is set to "_blank"?

Can't seem to capture the Referrer with PHP: $_SERVER['HTTP_REFERER']; Whenever visitors land on mywebsite.com from external-web-site.com via a link with target="_blank", for example: ... <a href="http://mywebsite.com" target ...

"Develop an interactive feature with jQuery that dynamically generates and removes fields according to the option selected from a

Can someone provide suggestions on how to achieve the functionality of adding and deleting input fields based on a user's selection from a drop-down menu using jQuery? I have successfully added the input fields, but I'm facing some confusion rega ...

Dealing with Jquery AJAX requests to NLB and navigating the challenges of cross-domain scripting restrictions

I am currently working on a dashboard application that utilizes Jquery AJAX calls to interact with a RESTFUL WCF service. Everything runs smoothly when the UI application and service are on the same server. However, due to issues with cross site scripting ...

Tips for acquiring offspring who are exclusively not descendants of a particular node

Currently, I am utilizing jQuery and my goal is to access all elements of a specific type that are not children of a particular node type. For example, my Document Object Model (DOM) structure looks like this: <div id='idthatiknow'> & ...