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 keys in objects that are inside the array

How can I sort the keys inside the object that is inside an array?

So I have a json file that has this data:

[
  {
    "name": "AAA",
    "age": 17,
    "location": "US"
  },
  {
    "age": 15,
    "name": "BBB",
    "location": "CA"
  },
  {
    "location": "NZ",
    "age": 10,
    "name": "CCC"
  }, ...
 ]

How can I possibly make the data like this:

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

[
  {
    "name": "AAA",
    "age": 17,
    "location": "US"
  },
  {
    "name": "BBB",
    "age": 15,
    "location": "CA"
  },
  {
  
    "name": "CCC",
    "age": 10,
    "location": "NZ"
  }, ...
 ]

>Solution :

Here is how you can sort the props of each object.

  1. map the array to modify its items
  2. Use Object.entries to convert its prop: value pairs into an array so you could sort them
  3. Convert them back to an object using Object.fromEntries.

The advantage of using this approach is that you don’t need to know the prop names in advance.

const source = [
  {
    "name": "AAA",
    "age": 17,
    "location": "US"
  },
  {
    "age": 15,
    "name": "BBB",
    "location": "CA"
  },
  {
    "location": "NZ",
    "age": 10,
    "name": "CCC"
  }
 ]

const sortedSource = source.map(item => {
  return Object.fromEntries(
    Object.entries(item).sort(([key1], [key2]) => {
      return key1.localeCompare(key2);
    })
  )
});

const stringify = obj => JSON.stringify(obj, null, 2);
console.log(stringify(source), stringify(sortedSource));

https://jsbin.com/fiwuyecuco/edit?js,console

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