-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' }
0

2 Answers 2

5
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
}
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

@Walk You cannot sort them either. Iteration-in-insertion-order is a helpful property for some algorithms, but it's far from indexed access.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.