-2

I need to sort JavaScript objects based on key length

Hence the following:

{ 'b' : 'asdsad', 'bbb' : 'masdas', 'bb' : 'dsfdsfsdf' }

Would become:

{ 'b' : 'dsfdsfsdf', 'bb' : 'dsfdsfsdf', 'bbb' : 'masdas' }
matisetorm
  • 847
  • 8
  • 21
Vittal Pai
  • 2,725
  • 18
  • 28

2 Answers2

4

There is no such concept as order for Javascript object properties, you can't sort them and then try to get by declaring order. Because there is no guarantee in which order they will appear.

From the EcmaScript 1 specification

4.3.3 Object

An object is a member of the type Object. It is an unordered collection of properties which contain primitive values, objects, or functions. A function stored in the property of an object is called a method.

If you need ordering, maybe it will be useful to look arrays.

Suren Srapyan
  • 57,890
  • 10
  • 97
  • 101
  • Or `Map`s! https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map – Walk Oct 17 '17 at 12:13
  • 1
    @Walk You cannot `sort` them either. Iteration-in-insertion-order is a helpful property for some algorithms, but it's far from indexed access. – Bergi Oct 17 '17 at 12:13
2
function TestA() {

  var a = {
    'b': 'asdsad',
    'bbb': 'masdas',
    'bb': 'dsfdsfsdf'
  }

  var keyArray = Object.keys(a);

  var object = {};

  keyArray.sort();

  keyArray.forEach(function(item) {

    object[item] = a[item]

  })
  return object
}
Walk
  • 675
  • 4
  • 13