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
This is possible using the
<Object>#keys
method.You can simply use
Object.keys
and sort it based on theirage
properties:If the snippet is confusing:
Object.keys
returns an array containing the keys in the objectsort
function takes a callback containing two parameters, where a positive value meansa
is greater, and a negative value meansb
is greater