简体   繁体   中英

Sort object by one of its values

I'm trying to sort an object by one of its values from least to greatest. For example:

{
    obj1: {
        key1: something,
        key2: 54,
        key3: "something else"
    },
    obj2:{
        key1: something,
        key2: 27,
        key3: "another thing"
    },
    obj3:{
        key1: anotherSomething,
        key2: 78,
        key3: "whatever"
    }
}

Should, when sorted by key2 , come out as obj2 , obj1 , obj3 . Is there any way I can do this?

PS I've seen that there were some similar threads to this on Stack Overflow, but they were sorting it by an object that wasn't nested ie { obj1: 5, obj2: 3, obj3: 8}

If you can't change the object to array (as you informed us in one of the comments), you could introduce an array with references to objects you wish to sort and then use the array to access those objects:

var obj = {
    obj1: {
        key1: something,
        key2: 54,
        key3: "something else"
    },
    obj2:{
        key1: something,
        key2: 27,
        key3: "another thing"
    },
    obj3:{
        key1: anotherSomething,
        key2: 78,
        key3: "whatever"
    }
};

var arr = [ obj.obj1, obj.obj2, obj.obj3 ];
arr.sort( function( a, b ){
   return a.key2 - b.key2;
} );

First of all, you need to convert your object to an array. This is a must, because object fields are not ordered by nature. Here's an example of such an array:

var arr =
[
    {
        key1: something,
        key2: 54,
        key3: "something else"
    },
    {
        key1: something,
        key2: 27,
        key3: "another thing"
    },
    {
        key1: anotherSomething,
        key2: 78,
        key3: "whatever"
    }
];

When you have an array, you can sort its elements in different ways. For example, if you use Underscore.js, you can do this:

_.sortBy(arr, 'key2');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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