按键对JavaScript对象进行排序

我需要按键对JavaScript对象进行排序。

因此,以下内容:

{ 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' }

会成为:

{ 'a' : 'dsfdsfsdf', 'b' : 'asdsad', 'c' : 'masdas' }
西门小卤蛋2020/03/12 18:07:19

The one line:

Object.entries(unordered)
  .sort(([keyA], [keyB]) => keyA > keyB)
  .reduce((obj, [key,value]) => Object.assign(obj, {[key]: value}), {})
Davaid阳光小卤蛋2020/03/12 18:07:19

Not sure if this answers the question, but this is what I needed.

Maps.iterate.sorted = function (o, callback) {
    var keys = Object.keys(o), sorted = keys.sort(), k; 
    if ( callback ) {
            var i = -1;
            while( ++i < sorted.length ) {
                    callback(k = sorted[i], o[k] );
            }
    }

    return sorted;
}

Called as :

Maps.iterate.sorted({c:1, b:2, a:100}, function(k, v) { ... } ) 
蛋蛋樱2020/03/12 18:07:19

This is a lightweight solution to everything I need for JSON sorting.

function sortObj(obj) {
    if (typeof obj !== "object" || obj === null)
        return obj;

    if (Array.isArray(obj))
        return obj.map((e) => sortObj(e)).sort();

    return Object.keys(obj).sort().reduce((sorted, k) => {
        sorted[k] = sortObj(obj[k]);
        return sorted;
    }, {});
}
Near飞云2020/03/12 18:07:19

Pure JavaScript answer to sort an Object. This is the only answer that I know of that will handle negative numbers. This function is for sorting numerical Objects.

Input obj = {1000: {}, -1200: {}, 10000: {}, 200: {}};

function osort(obj) {
var keys = Object.keys(obj);
var len = keys.length;
var rObj = [];
var rK = [];
var t = Object.keys(obj).length;
while(t > rK.length) {
    var l = null;
    for(var x in keys) {
        if(l && parseInt(keys[x]) < parseInt(l)) {
            l = keys[x];
            k = x;
        }
        if(!l) { // Find Lowest
            var l = keys[x];
            var k = x;
        }
    }
    delete keys[k];
    rK.push(l);
}

for (var i = 0; i < len; i++) {

    k = rK[i];
    rObj.push(obj[k]);
}
return rObj;
}

The output will be an object sorted by those numbers with new keys starting at 0.

JinJin神奇宝儿2020/03/12 18:07:19
Object.keys(unordered).sort().reduce(
    (acc,curr) => ({...acc, [curr]:unordered[curr]})
    , {}
)
神无十三2020/03/12 18:07:19

Here is a clean lodash-based version that works with nested objects

/**
 * Sort of the keys of an object alphabetically
 */
const sortKeys = function(obj) {
  if(_.isArray(obj)) {
    return obj.map(sortKeys);
  }
  if(_.isObject(obj)) {
    return _.fromPairs(_.keys(obj).sort().map(key => [key, sortKeys(obj[key])]));
  }
  return obj;
};

It would be even cleaner if lodash had a toObject() method...

猴子Harry2020/03/12 18:07:19

Use this code if you have nested objects or if you have nested array obj.

var sortObjectByKey = function(obj){
    var keys = [];
    var sorted_obj = {};
    for(var key in obj){
        if(obj.hasOwnProperty(key)){
            keys.push(key);
        }
    }
    // sort keys
    keys.sort();

    // create new array based on Sorted Keys
    jQuery.each(keys, function(i, key){
        var val = obj[key];
        if(val instanceof Array){
            //do for loop;
            var arr = [];
            jQuery.each(val,function(){
                arr.push(sortObjectByKey(this));
            }); 
            val = arr;

        }else if(val instanceof Object){
            val = sortObjectByKey(val)
        }
        sorted_obj[key] = val;
    });
    return sorted_obj;
};
NearL2020/03/12 18:07:19

Sorts keys recursively while preserving references.

function sortKeys(o){
    if(o && o.constructor === Array)
        o.forEach(i=>sortKeys(i));
    else if(o && o.constructor === Object)
        Object.entries(o).sort((a,b)=>a[0]>b[0]?1:-1).forEach(e=>{
            sortKeys(e[1]);
            delete o[e[0]];
            o[e[0]] = e[1];
        });
}

Example:

let x = {d:3, c:{g:20, a:[3,2,{s:200, a:100}]}, a:1};
let y = x.c;
let z = x.c.a[2];
sortKeys(x);
console.log(x); // {a: 1, c: {a: [3, 2, {a: 1, s: 2}], g: 2}, d: 3}
console.log(y); // {a: [3, 2, {a: 100, s: 200}}, g: 20}
console.log(z); // {a: 100, s: 200}
MandyL2020/03/12 18:07:19

也许更优雅的形式:

 /**
     * Sorts a key-value object by key, maintaining key to data correlations.
     * @param {Object} src  key-value object
     * @returns {Object}
     */
var ksort = function ( src ) {
      var keys = Object.keys( src ),
          target = {};
      keys.sort();
      keys.forEach(function ( key ) {
        target[ key ] = src[ key ];
      });
      return target;
    };


// Usage
console.log(ksort({
  a:1,
  c:3,
  b:2  
}));

PS和ES6 +语法相同:

function ksort( src ) {
  const keys = Object.keys( src );
  keys.sort();
  return keys.reduce(( target, key ) => {
        target[ key ] = src[ key ];
        return target;
  }, {});
};
猴子阳光2020/03/12 18:07:19

假设它在显示无序对象属性的VisualStudio调试器中很有用。

(function(s){var t={};Object.keys(s).sort().forEach(function(k){t[k]=s[k]});return t})({b:2,a:1,c:3})
樱Davaid2020/03/12 18:07:19

下划线版本

function order(unordered)
{
return _.object(_.sortBy(_.pairs(unordered),function(o){return o[0]}));
}

如果您不信任浏览器来保持键的顺序,我强烈建议您使用键-值对数组的有序数组。

_.sortBy(_.pairs(c),function(o){return o[0]})
仲羽蛋蛋2020/03/12 18:07:19

这是一个古老的问题,但是从Mathias Bynens的回答中可以得出,我做了一个简短的版本来对当前对象进行排序,而没有太多的开销。

    Object.keys(unordered).sort().forEach(function(key) {
        var value = unordered[key];
        delete unordered[key];
        unordered[key] = value;
    });

执行代码后,“无序”对象本身将按字母顺序对键进行排序。

L西里2020/03/12 18:07:18

现在是2019年,我们有一种解决这个问题的2019年方法:)

Object.fromEntries(Object.entries({b: 3, a:8, c:1}).sort())
GOItachi老丝2020/03/12 18:07:18

很多人提到“无法对对象进行排序”,但是之后他们为您提供了可行的解决方案。悖论,不是吗?

没有人提到为什么这些解决方案有效。之所以这样,是因为在大多数浏览器的实现中,对象中的值都是按添加顺序存储的。这就是为什么如果您从键的排序列表中创建新对象,则会返回预期的结果。

而且我认为我们可以添加另一种解决方案– ES5功能方式:

function sortObject(obj) {
    return Object.keys(obj).sort().reduce(function (result, key) {
        result[key] = obj[key];
        return result;
    }, {});
}

ES2015以上版本(格式为“单线”):

function sortObject(o) {
    return Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {});
}

以上示例的简短说明(如评论中所述):

Object.keys向我们提供了提供的对象(objo中的键列表,然后我们使用默认的排序算法对键进行排序,接下来.reduce将其用于将该数组转换回对象,但是这次所有键都已排序。