Is there a way to sort/order keys in JavaScript objects?

后端 未结 7 2191
故里飘歌
故里飘歌 2020-11-28 08:16

For example the following

var data = {
    \'States\': [\'NSW\', \'VIC\'],
    \'Countries\': [\'GBR\', \'AUS\'],
    \'Capitals\': [\'SYD\', \'MEL\']
}
for          


        
7条回答
  •  心在旅途
    2020-11-28 08:59

    here's a nice functional solution:

    basically,

    1. extract the keys into a list with Object.keys
    2. sort the keys
    3. reduce list back down to an object to get desired result

    ES5 Solution:

    not_sorted = {b: false, a: true};
    
    sorted = Object.keys(not_sorted)
        .sort()
        .reduce(function (acc, key) { 
            acc[key] = not_sorted[key];
            return acc;
        }, {});
    
    console.log(sorted) //{a: true, b: false}
    

    ES6 Solution:

    not_sorted = {b: false, a: true}
    
    sorted = Object.keys(not_sorted)
        .sort()
        .reduce((acc, key) => ({
            ...acc, [key]: not_sorted[key]
        }), {})
    
    console.log(sorted) //{a: true, b: false}
    

提交回复
热议问题