skip to Main Content

I was wondering if i can sort the json keys in order as an array by the values.

Below is a json object

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

and i want it to get sorted in array/text in ascending order by the values of the subkey "age".
["p2", "p1", "p3"]

I haven’t tried anything as I have no idea what to do, can someone return me an example…

2

Answers


  1. This is possible using the <Object>#keys method.

    const obj = {
        "p1": {
            "name": "*****",
            "age": "18"
        },
        "p2": {
            "name": "*****",
            "age": "14"
        },
        "p3": {
            "name": "*****",
            "age": "24"
        }
    }
    const keys = Object.keys(obj);
    
    // Then sort
    const sorted = keys.sort((a, b) => parseInt(obj[a].age) - parseInt(obj[b].age));
    
    Login or Signup to reply.
  2. You can simply use Object.keys and sort it based on their age properties:

    const data = { "p1": { "name": "*****", "age": "18" }, "p2": { "name": "*****", "age": "14" }, "p3": { "name": "*****", "age": "24" }}
    
    const dataKeysSortedByAge = Object.keys(data).sort((a, b) => data[a].age - data[b].age)
    console.log(dataKeysSortedByAge)

    If the snippet is confusing:

    1. Object.keys returns an array containing the keys in the object
    2. The sort function takes a callback containing two parameters, where a positive value means a is greater, and a negative value means b is greater
    3. We subtract one property’s age from the other one; we can be lazy here and not convert the values to a number because substraction coerces the values to numbers
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search