Arrange the Json array by key value in a different order

I have a contact list that is returning in a lengthy form, organized based on order of entry. I am looking to alphabetically sort the list by displayName which is nested within the main array. Can anyone assist with this challenge using JavaScript? Thank you for any help provided!

{
"0":
{"id":1,"rawId":null,"displayName":"Person 1","name":null,"nickname":null,"phoneNumbers":[{"type":"mobile","value":"phonenumb53534r","id":0,"pref":false}],"emails":null,"addresses":null,"ims":null,"organizations":null,"birthday":null,"note":null,"photos":null,"categories":null,"urls":null},
"1":
{"id":2,"rawId":null,"displayName":"Person 2","name":null,"nickname":null,"phoneNumbers":[{"type":"mobile","value":"phonenumber535345","id":0,"pref":false}],"emails":null,"addresses":null,"ims":null,"organizations":null,"birthday":null,"note":null,"photos":null,"categories":null,"urls":null},
"2":
{"id":3,"rawId":null,"displayName":"Person 3","name":null,"nickname":null,"phoneNumbers":[{"type":"mobile","value":"phonenumber47474","id":0,"pref":false}],"emails":null,"addresses":null,"ims":null,"organizations":null,"birthday":null,"note":null,"photos":null,"categories":null,"urls":null}, more entries follow 

Answer №1

JavaScript objects do not have a built-in order. When dealing with arrays, you can manipulate them directly. However, if you are working with objects, you need to convert them into an array first:

var arrayOfObjects = [];

for (item in object) {
    if (object.hasOwnProperty(item)) {
        arrayOfObjects.push(object[item]);
    }
}

It would be ideal to perform this conversion even before receiving the JSON data. Once you have the array of objects, you can easily sort it using the standard .sort method.

arrayOfObjects.sort(function (a, b) {
    if (a.name < b.name) {
        return -1;
    } else if (a.name > b.name) {
        return 1;
    }
    return 0;
});

http://jsfiddle.net/YzP8T/

Answer №2

To utilize the responseText, you must first convert it into JSON format. This initial format will need to be transformed into an array before sorting can occur using a custom function comparator.

let jsonData = JSON.parse(response);
let dataArray = [];

for (let prop in jsonData) {
    dataArray.push(jsonData[prop]);
}

dataArray.sort(function (x, y) {
    return x.name > y.name;
});

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

There seems to be an issue with Jquery not triggering the Webservice method in the Firefox browser, despite it working successfully in Chrome

Currently, I have an issue where a webservice method called via ajax in jQuery is functioning correctly in Chrome and IE browsers but not in Firefox. Here is the jQuery code: $("#btnUpdate").click(function () { var objEmp = { employeeID: $("#Em ...

Expanding Java Classes and Replacing Methods with Multiple Parameters in ES4X/Graal

I am currently facing a challenge in my JavaScript project using ES4X/Graal, where I need to extend a Java class. This Java class has methods with overloaded parameters that I must override. While I understand how to call a specific Java method by specifyi ...

Creating a JavaScript anchor through a backend bean function

Is it crazy to want to create an anchor that can be called from a backing bean method using JavaScript? I need to do this for specific reasons, utilizing a commandButton with ajax set to false. I'm attempting the following approach: RequestContext.g ...

Error: Attempting to use the 'append' method on an object that does not support the FormData interface

$(document).on('submit','#form_pem', function(event){ event.preventDefault(); var kode = $('#kode').val(); var name = $('#name').val; var price = $('#price'). ...

What is causing my Fabric.js canvas to malfunction?

Here is the link to my JSFiddle project: http://jsfiddle.net/UTf87/ I am facing an issue where the rectangle I intended to display on my canvas is not showing up. Can anyone help me figure out why? HTML: <div id="CanvasContainer"> <canvas id ...

Tips for ensuring an animation is triggered only after Angular has fully initialized

Within this demonstration, the use of the dashOffset property initiates the animation for the dash-offset. For instance, upon entering a new percentage in the input field, the animation is activated. The code responsible for updating the dashOffset state ...

"Make sure to tick the checkbox if it's not already selected,

Could use some assistance with traversing and logic in this scenario. Here is the logic breakdown: If any checkbox in column3 is checked, then check the first column checkbox. If none in column 3 are selected, uncheck checkbox in column1. If column1 ...

The utility of commander.js demonstrated in a straightforward example: utilizing a single file argument

Many developers rely on the commander npm package for command-line parsing. I am considering using it as well due to its advanced functionality, such as commands, help, and option flags. For my initial program version, I only require commander to parse ar ...

Incorporating a swisstopo map from an external source into an Angular

I am looking to integrate a swisstopo map into my angular 8 app. As I am new to angular, I am unsure how to include this example in my component: I have tried adding the script link to my index.html file and it loads successfully. However, I am confused a ...

What methods can be used to get npx to execute a JavaScript cli script on a Windows operating system

The Issue - While my npx scaffolding script runs smoothly on Linux, it encounters difficulties on Windows. I've noticed that many packages run flawlessly on Windows, but the difference in their operations remains elusive to me. Even after consulting A ...

Retrieve information from a controller and pass it to a Component in AngularJs

Having an issue with passing data from a controller to a component in AngularJs. The data is successfully passed to the template component, but it shows up as undefined in the controller! See below for my code snippets. The controller angular.module(&a ...

Issue with MVC 4 C# - Implementing column chart visualization using json object in Google chart

In my MVC 4 application using C#, I'm incorporating the Google Visualization API column chart to display data graphics. However, recently I've been facing a bug that affects the visualization of the information despite the data being correct. He ...

Utilize data binding in Typescript to easily link variables between a service and controller for seamless utilization

Is there a way to overcome the issue of value assignment not binding data in this scenario? For example, using this.arrayVal = someService.arrayVal does not work as intended. The objective is to simplify the assignment in both HTML and controller by using ...

What is the reason for Vue not updating the component after the Pinia state is modified (when deleting an object from an Array)?

When using my deleteHandler function in pinia, I noticed an issue where the users array was not being re-rendered even though the state changed in vue devtools. Interestingly, if I modify values within the array instead of deleting an object from it, Vue ...

Learn how to integrate ES6 features into your nodejs/expressjs application using either Gulp or Webpack

I am looking to incorporate ES6 features into my nodejs/expressjs application. Currently, I am using Gulp for JavaScript compilation and setting up live reload. What steps do I need to take in order to compile the es6 code to standard js within my exis ...

The communication breakdown between Jquery and PHP caused a malfunction

Apologies for the questions, but I am stuck on this minor issue. Being a rookie has its effects :) I have a JSON format representing a list of games with rounds and player information for each round. In this example, only 1 game with 3 rounds is shown: { ...

Angular rxjs: Wait for another Observable to emit before subscribing

My setup involves having 2 subscriptions - one is related to my ActivatedRoute, and the other is from ngrx Store. ngOnInit() { this.menuItems$ = this.store.select('menuItems'); this.menuItems$.subscribe(data => { this.menuItem ...

A beginner's guide to using Jasmine to test $http requests in AngularJS

I'm struggling with testing the data received from an $http request in my controller as I don't have much experience with Angular. Whenever I try to access $scope, it always comes back as undefined. Additionally, fetching the data from the test ...

What is the best way to showcase top-rated posts from my feed of posts?

I have a basic PHP script that allows users to post without logging in. Once they submit their posts, the posts are displayed below in a feed similar to Facebook's news feed. I'm now looking to extract the three most liked posts and display them ...

Can an action be activated when the mouse comes to a halt?

Currently, I am having trouble triggering an event when a user stops moving their mouse over a div element. The current event is set up to show and follow another element along with the mouse movement, but I want it to only display when the mouse stops mov ...