Reputation: 580
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"
Upvotes: 0
Views: 6961
Reputation: 152
Do two arrays:
// 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]]);
Upvotes: 0
Reputation: 322
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;
}
Upvotes: 1
Reputation: 86
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.
Upvotes: 2