Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
How to sort a nested object based on key name

I have a nested object that looks like this.I want to sort this in ascending and descending order based on the alphabetical order of Districtnames.

var data = 
{"DistrictC":{"population":105597},
"DistrictB":{"population":36842},
"DistrictA":{"population":238142}}

Expected output in ascending order is shown below.I also need to sort in descending order.

{"DistrictA":{"population":238142},
"DistrictB":{"population":36842},
"DistrictC":{"population":105597}}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You could use Object.entries to get an array of key/value pairs and then sort on the keys using localeCompare:

const data = {
  "DistrictC":{"population":105597},
  "DistrictB":{"population":36842},
  "DistrictA":{"population":238142}
}

const sorted = Object.entries(data)
  .sort(([keyA], [keyB]) => keyA.localeCompare(keyB));

console.log(sorted);

You could make that result a bit easier to work with by collapsing the key/value arrays into objects using map:

// same as before
const data = {
  "DistrictC":{"population":105597},
  "DistrictB":{"population":36842},
  "DistrictA":{"population":238142}
}

// same as before
const sorted = Object.entries(data)
  .sort(([keyA], [keyB]) => keyA.localeCompare(keyB));

const collapsed = sorted.map(([district, value]) => ({ district, ...value }));

// ascending
console.log(collapsed);

// descending
console.log(collapsed.reverse());

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!