简体   繁体   English

按字母顺序对关联数组/ javascript对象进行排序

[英]Sorting associative array / javascript object by keys alphabetically

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) (Statdev是一个字符串,而kartnr和bitnrk是整数)

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): 一些Firebug输出(我还注意到在Firebug中,对象按字母顺序排序):

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"

In JavaScript impossible to sort object properties by keys. 在JavaScript中,无法通过键对对象属性进行排序。 If you need it, you can put to array all keys of object, to sort them and then work with properties in desired order. 如果需要,可以将对象的所有键放入数组,对其进行排序,然后按所需顺序使用属性。

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;
}

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]]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM