-2

I've been looking for a while and want a way to sort a Javascript object like this:

[{"a":"111","C":"333","B":"222"},{{"A":"111","C":"333","B":"222"}]

and sort is alphabetically by name to get:

[{"a":"111","B":"222","C":"333"},{{"A":"111","B":"222","C":"333"}]

Please suggest any solution

Özgür Ersil
  • 6,909
  • 3
  • 19
  • 29

2 Answers2

1

This question has been answered here:

Sort Keys in Javascript Object

Basically, you can't sort the keys in a JavaScript object. They are unordered. You can think of it essentially as a hash. You have to extract it into an array in order to sort.

var obj = {a: 'Hi', b: 'There'};
Object.keys(obj).sort().map(k => { 
  var foo = {}; 
  foo[k] = obj[k]; 
  return foo; 
});

That will give you an array that looks like this: [{a: 'Hi'}, {b: 'There'}]. And that's about the best you can do.

Community
  • 1
  • 1
Christopher Davies
  • 4,461
  • 2
  • 34
  • 33
0

actually you can sort it but only in case if your keys are numeric strings.

here you can see other solutions

Sorting JavaScript Object by property value

Community
  • 1
  • 1
Ignat Galkin
  • 597
  • 1
  • 4
  • 11