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…
>Solution :
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:
Object.keysreturns an array containing the keys in the object- The
sortfunction takes a callback containing two parameters, where a positive value meansais greater, and a negative value meansbis greater - 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