如果我有一个JavaScript对象,如:

var list = {
  "you": 100, 
  "me": 75, 
  "foo": 116, 
  "bar": 15
};

是否有一种方法可以根据值对属性进行排序?最后得到

list = {
  "bar": 15, 
  "me": 75, 
  "you": 100, 
  "foo": 116
};

当前回答

var list = {
    "you": 100, 
    "me": 75, 
    "foo": 116, 
    "bar": 15
};

function sortAssocObject(list) {
    var sortable = [];
    for (var key in list) {
        sortable.push([key, list[key]]);
    }
    // [["you",100],["me",75],["foo",116],["bar",15]]

    sortable.sort(function(a, b) {
        return (a[1] < b[1] ? -1 : (a[1] > b[1] ? 1 : 0));
    });
    // [["bar",15],["me",75],["you",100],["foo",116]]

    var orderedList = {};
    for (var idx in sortable) {
        orderedList[sortable[idx][0]] = sortable[idx][1];
    }

    return orderedList;
}

sortAssocObject(list);

// {bar: 15, me: 75, you: 100, foo: 116}

其他回答

另一个关于Object的例子。值、sort()和展开运算符。

var paintings = {
    0: {
        title: 'Oh my!',
        year: '2020',
        price: '3000'
    },
    1: {
        title: 'Portrait V',
        year: '2021',
        price: '2000'
    },
    2: {
        title: 'The last leaf',
        year: '2005',
        price: '600'
    }
}

我们使用object .values将对象转换为对象数组:

var toArray = Object.values(paintings)

然后我们对数组进行排序(按年份和价格),使用spread操作符使原始数组不可变,并使用sort()方法对数组进行排序:

var sortedByYear = [...toArray].sort((a, b) => a.year - b.year)
var sortedByPrice = [...toArray].sort((a, b) => a.price - b.price)

最后,我们生成新的排序对象(同样,使用展开运算符来保持以[x: number]为键的对象的object的原始形式):

var paintingsSortedByYear = {
    ...sortedByYear
}

var paintingsSortedByPrice = {
    ...sortedByPrice
}

希望这对你有所帮助!

你的对象可以有任意数量的属性,如果你把对象放在数组中,你可以选择根据你想要的任何对象属性进行排序,数字或字符串。考虑这个数组:

var arrayOfObjects = [   
    {
        name: 'Diana',
        born: 1373925600000, // Mon, Jul 15 2013
        num: 4,
        sex: 'female'
    },
    {

        name: 'Beyonce',
        born: 1366832953000, // Wed, Apr 24 2013
        num: 2,
        sex: 'female'
    },
    {            
        name: 'Albert',
        born: 1370288700000, // Mon, Jun 3 2013
        num: 3,
        sex: 'male'
    },    
    {
        name: 'Doris',
        born: 1354412087000, // Sat, Dec 1 2012
        num: 1,
        sex: 'female'
    }
];

按出生日期排序,最年长的先

// use slice() to copy the array and not just make a reference
var byDate = arrayOfObjects.slice(0);
byDate.sort(function(a,b) {
    return a.born - b.born;
});
console.log('by date:');
console.log(byDate);

按名称排序

var byName = arrayOfObjects.slice(0);
byName.sort(function(a,b) {
    var x = a.name.toLowerCase();
    var y = b.name.toLowerCase();
    return x < y ? -1 : x > y ? 1 : 0;
});

console.log('by name:');
console.log(byName);

http://jsfiddle.net/xsM5s/16/

JavaScript对象根据定义是无序的(参见ECMAScript语言) 规范,第8.6节)。语言规范甚至不能保证,如果你连续迭代一个对象的属性两次,第二次它们会以相同的顺序出现。

如果你需要对事物进行排序,可以使用数组和array .prototype.sort方法。

输入是对象,输出是对象,使用lodash & js内置库,降序或升序选项,不改变输入对象

Eg输入输出

{
  "a": 1,
  "b": 4,
  "c": 0,
  "d": 2
}
{
  "b": 4,
  "d": 2,
  "a": 1,
  "c": 0
}

实现

const _ = require('lodash');

const o = { a: 1, b: 4, c: 0, d: 2 };


function sortByValue(object, descending = true) {
  const { max, min } = Math;
  const selector = descending ? max : min;

  const objects = [];
  const cloned = _.clone(object);

  while (!_.isEmpty(cloned)) {
    const selectedValue = selector(...Object.values(cloned));
    const [key, value] = Object.entries(cloned).find(([, value]) => value === selectedValue);

    objects.push({ [key]: value });
    delete cloned[key];
  }

  return _.merge(...objects);
}

const o2 = sortByValue(o);
console.log(JSON.stringify(o2, null, 2));
    var list = {
    "you": 100,
    "me": 75,
    "foo": 116,
    "bar": 15
};
var tmpList = {};
while (Object.keys(list).length) {
    var key = Object.keys(list).reduce((a, b) => list[a] > list[b] ? a : b);
    tmpList[key] = list[key];
    delete list[key];
}
list = tmpList;
console.log(list); // { foo: 116, you: 100, me: 75, bar: 15 }