简体   繁体   中英

How to sort this javascript array of objects by its keys?

I have an array similar to this one in a JSON file.

data = {
    "foo" : {
        "08" : {"bar": "1", "baz":"2"},
        "09" : {"bar": "3", "baz":"10"},
        "10" : {"bar": "5", "baz":"3"},
        "11" : {"bar": "8", "baz":"8"},
        "12" : {"bar": "9", "baz":"8"}
     },
     "foo_2" : {
        "01" : {"bar": "1", "baz":"2"},
        "02" : {"bar": "1", "baz":"2"}
        //03, 04 and so on..
     }
}

Let's say I want to get the objects from the first foo key, so using data.foo will do just fine. Now, when iterating through data.foo , the indexes will not come in the order shown on the file. I think it's due to the fact the indexes are strings instead of numbers, but still, they'll come in the following order:

{
    "12" : {"bar": "9", "baz":"8"},
    "11" : {"bar": "8", "baz":"8"},
    "10" : {"bar": "5", "baz":"3"},
    "08" : {"bar": "1", "baz":"2"},
    "09" : {"bar": "3", "baz":"10"}
}

Tried many things here and did a lot of reasearch here in SO but found few topics on the subject and they all will sort the array based in a value deep inside the array, like bar for example.

how would you sort this array only by those first numbered indexes, so they come out just like they're organized in the file ?

Ok, got it to work based on the comment from @palanik, thank you very much, man !

here's how:

// variable which receives the selected object to iterate through
var foo = data.foo;

// here we sort the keys out of the array of objects and map them to another variable,
// sorting by the keys as numbers instead of strings, using the parseInt() function
var sortedArray = Object.keys(foo).sort(function(a,b){
    return parseInt(a,10) - parseInt(b,10);
}).map(function(sortedKeys){
    return foo[sortedKeys];
});

console.log(sortedArray);
// returns the array of values without the keys, but in the desired order, like this
//[
//    {"bar": "1", "baz":"2"},
//    {"bar": "3", "baz":"10"},
//    {"bar": "5", "baz":"3"},
//    {"bar": "8", "baz":"8"},
//    {"bar": "9", "baz":"8"}
//]

Posting in the hope someone else won't lose their whole day trying to figure out something so simple (like I just did) out there lol...

Thank you guys for the insightful comments above and again, thanks palanik ! :)

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