0

How do i order this object by the keys, Alphabetically?

I tried:

racks.sort();

The object racks is filled like this:

(Statdev is a string, and kartnr and bitnrk are integers)

racks[jPunten[i].STATDEV] = {
                            label: '',
                            punkt: [{
                            x: jPunten[i].KARTNR,
                            y: jPunten[i].BITNRK}]

Some Firebug output (i also noticed that in firebug the object IS ordered alphabetically):

racks
    []

DAY
    Object { punkt=[8], label=""}

label
    ""

punkt
    [Object { x="12", y="1"}, Object { x="12", y="2"}, Object { x="12", y="3"}, 5 meer...]

0
    Object { x="12", y="1"}

1
    Object { x="12", y="2"}

2
    Object { x="12", y="3"}

3
    Object { x="12", y="4"}

4
    Object { x="12", y="5"}

5
    Object { x="12", y="6"}

6
    Object { x="12", y="7"}

7
    Object { x="12", y="8"}

LSF01
    Object { punkt=[1], label=""}

label
    ""

punkt
    [Object { x="1", y="10"}]

0
    Object { x="1", y="10"}

x
    "1"

y
    "10"
2
  • There is no inherent order in JavaScript objects. If you need a reliable sorting, create an array of keys and sort that. Commented Nov 14, 2013 at 13:07
  • You can't sort objects. They are sorted by key names automatically (in most cases). Commented Nov 14, 2013 at 13:07

3 Answers 3

2

In JavaScript impossible to sort object properties by keys. If you need it, you can put to array all keys of object, to sort them and then work with properties in desired order.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

sort = function(obj, comparator) {
    var array = [];
    for (var i in obj) {
        array.push([obj[i], i]);
    }
    array.sort(function(o1, o2) {
        return comparator(o1[0], o2[0]);
    });
    var newObj = {};
    for (var i = 0; i < array.length; i++) {
        newObj[array[i][1]] = array[i][0];
    }
    return newObj;
}

1 Comment

What is the comparator? Can you give an example?
0

Do two arrays:

  • one array for the keys
  • the second associative array, using the key value pair, is actually an object.

// normal object notation

var personObject = {firstName:"John", lastName:"Doe"};
alert('personObject.firstName - ' + personObject.firstName);

// add to object using object-array notation, note: doing this will convert an array to an object

personObject["age"] = 46;

// array of keys, sorted

var keysArray = ["firstName", "lastName"];
keysArray[keysArray.length] = "age";
keysArray.sort();

// get object value, using array-object notation with array as key

alert('personObject[keysArray[0]] - ' + personObject[keysArray[0]]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.