Javascript : Sort Associative array using value property without converting into Array of objects

时间:2016-04-07 10:55:17

标签: javascript associative-array

I need to sort associative array by value (using "position" value as shown below). I tried by converting into array. It is working fine. But I wanted to know, Is there any other way of doing it?

{  
   "CAB":{
           name:CBSSP,
           position:2
         },
   "NSG":{  
           name:NNSSP,
           position:3
         },
   "EQU":{  
           name:SSP,
           position:1
         }
}

3 个答案:

答案 0 :(得分:1)

您也可以尝试:

Object.keys(o).map(function(key){return o[key];})
              .sort(function(p, c){return  p.position - c.position})

答案 1 :(得分:0)

JavaScript中没有关联数组,您拥有的是一个对象,其属性为CABNSGEQU

对象属性不能保证设置顺序,因此解决方案是使用对象数组,因为数组确实保证了顺序。

答案 2 :(得分:0)

您可以使用订单数组来对对象进行有序引用。您需要更正位置,因为数组是基于零的。

var object = { "CAB": { name: 'CBSSP', position: 2 }, "NSG": { name: 'NNSSP', position: 3 }, "EQU": { name: 'SSP', position: 1 } },
    order = [];

Object.keys(object).forEach(function (k) {
    return order[object[k].position - 1] = k;
});

document.write('<pre>' + JSON.stringify(order, 0, 4) + '</pre>');