Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort Json Object in an array/text

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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:

  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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading