Arranging JSON Objects within an array or text

I am curious if it is possible to arrange the keys in a JSON object as an array based on their values.

Here is the JSON object:

{
  "p1": {
    "name": "*****",
    "age": "18"
  },
  "p2": {
    "name": "*****",
    "age": "14"
  },
  "p3": {
    "name": "*****",
    "age": "24"
  }
}

I want to sort them in ascending order by the value of the subkey "age," like this:

["p2", "p1", "p3"]

I haven't attempted anything yet because I'm not sure how. Could someone provide me with an example?

Answer №1

To organize the data based on their age properties, you can utilize the Object.keys method:

const information = { "person1": { "name": "*****", "age": "18" }, "person2": { "name": "*****", "age": "14" }, "person3": { "name": "*****", "age": "24" }}

const sortedDataByAge = Object.keys(information).sort((x, y) => information[x].age - information[y].age)
console.log(sortedDataByAge)

If the code snippet seems complex:

  1. Object.keys generates an array with the object's keys
  2. The sort function has a callback with two parameters; if the result is positive, then x is greater, and if negative, then y is greater
  3. We subtract one age property from another; no need to convert the values to numbers as subtraction coerces them to be numeric

Answer №2

To achieve this, you can make use of the <Object> method called #keys.

const objDetails = {
    "p1": {
        "name": "Jane Doe",
        "age": "28"
    },
    "p4": {
        "name": "John Smith",
        "age": "32"
    },
    "p7": {
        "name": "Alice Johnson",
        "age": "22"
    }
}
const keysArr = Object.keys(objDetails);

// Next, sort the keys
const sortedKeys = keysArr.sort((x, y) => parseInt(objDetails[x].age) - parseInt(objDetails[y].age));

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

I am struggling to parse a specific JSON file

A json file contains a variable number of elements that describe keywords. Here is an example: {"keywords":[{"keyword":"halloween","score":0.9621220167107003}, {"keyword":"pumpkin","score&quo ...

Looking up results in an array in PHP/MySQL

I have retrieved the results from mysql ($date_options) as shown below: Array ( [0] => stdClass Object ( [id] => 4 [start_date] => 2010-09-29 ) [1] => stdClass Object ( [id] => 13 [start_date] =&g ...

Is it possible to use vanilla JavaScript scroll event with AngularJS framework?

I am attempting to track the window offset from the top of the document, but I am facing issues with jQuery scroll functionality. Can a vanilla JavaScript scroll event listener be used effectively within an Angular environment? app.directive('owlCaro ...

Try employing an alternative angular controller when working with the bootstrap modal

I am trying to implement a bootstrap modal in my main HTML file, and I need some help on how to call another Angular controller for the modal. The button that triggers the modal is within a div that already has an Angular controller, and this is causing th ...

Saving the output of an AngularJS expression in an input field

Looking at the calculations below, I am currently evaluating an expression, {{ annualIncome * 4.5 }}, in one input and then re-evaluating the same expression in another input. Instead of saving the result and transferring it to the other input, I am repeat ...

Using Chrome Developer Tool to extract information such as names, addresses, and phone numbers from directory sites like TruePeopleSearch.com

Hey everyone! I'm currently in the process of expanding my knowledge on data parsing using Python. Lately, I've been exploring how to use Chrome Developer Tools effectively. One thing that's got me stumped is figuring out how to copy or view ...

Index beyond bounds of array

As I approach the completion of my assignment, I am encountering a challenge while attempting to create a map using a nested for loop. Below is the code segment along with the error message that I am facing: public void draw(){ System.out.println("Initia ...

Using Javascript and jQuery to convert text into a tag

I'm attempting to use JavaScript to send a message on twitch.tv by modifying the textarea in the chatbox. <textarea class="tw-textarea tw-textarea--no-resize " placeholder="Send message" data-a-target="chat-input" data-test-selector="chat-input" s ...

Difficulty with collapsing and expanding levels in Bootstrap 4 sidebar navigation

Having some trouble with my vertical Nav created using bootstrap 4. I have 2 levels of lists, but when I click on one dropdown, the other dropdown doesn't close. Here is a link to the issue: https://jsfiddle.net/thilanka/cr0Lfmd1 <ul class="na ...

I'm looking for a simple calendar widget that can be clicked on using only plain JavaScript/jQuery and is compatible with Bootstrap

I'm in search of a simple clickable calendar widget to integrate into my website. I am using a combination of HTML, CSS, Bootstrap 5, and jQuery 3.6 for development. The functionality I require is for the calendar days to be clickable so that I can di ...

Retrieving properties from a URL pathname using React.js

Struggling to retrieve the uid and token from the URL pathname in my React application using the match method. However, encountered an error: Uncaught TypeError: n is undefined Here's the snippet of the code: const ResetPasswordConfirm = ( {match, ...

Send a vanilla JavaScript ajaxForm submission by completing the form

I am currently in the process of integrating JavaScript from an iOS application into a web application. I have control over the code for both apps. My objective is to develop a JavaScript function that can receive input from a barcode scanner, populate a w ...

Add the arrivalDate value to the existing array

Is there a way to store each arrivalDate from the API's JSON response into my array list, even though the array is currently empty? Here is a snippet of the JSON returned by the API: { "reservations": { "reservationInfo&quo ...

What is AngularJs's preference: URL or ID for templateUrl?

When looking at the AngularJS documentation, you will come across an example using the templateUrl property: In the HTML: //ngApp... <div ng-controller="Ctrl"> <div my-customer></div> </div> And in the controller: . ...

Effortlessly glide to the top of the webpage

After dedicating numerous hours to this task and being a newcomer to JavaScript/JQuery, I am still unsure of how to achieve the following: I have implemented a "back to top" anchor link in the footer of my pages that directs users back to the header. I am ...

Guidance on invoking the navigate function from a component displayed at the highest level of rendering

Within the react-navigation documentation, it is explained that you can initiate navigation from the top-level component using the following method: import { NavigationActions } from 'react-navigation'; const AppNavigator = StackNavigator(SomeA ...

Dealing with special characters in Mustache.js: handling the forward slash

I have a JSON file that contains information about a product. Here is an example of the data: { "products": [ { "title": "United Colors of Benetton Men's Shirt", "description": "Cool, breezy and charming – this s ...

Utilizing WordPress Variables Beyond the Loop

Following the update of my loop to gather all necessary data using this code: <?php $json = ""; if ( have_posts() ) { while ( have_posts() ) { the_post(); global $wpdb; $query = "SELECT * FROM ". $wpdb-&g ...

Using Laravel with Ajax to retrieve complete data from a joined table

When attempting to retrieve the name from the 'users' table, the entire user object is being returned in the network tab. This leaks private information such as phone numbers which are stored in the users table. Here is the Admin Model: class Ad ...

Repetitive invocation of functions

I am presenting a listing HTML structure as follows <li class="game-box showlist" id="papp_1249" data-tag="Junior KG,Maths"> <div class="game-box-link" data-id="1249" data-active="yes" data-orientation="landscape" data-ajax="fal ...