0

I have an object that looks like:

{

    "2013": {
        "name": 2013,
        "ts_create": 1375254000000,
        "view_url": "some_url",
        "save_url": "some_url_2",
        "id": "",
        "exists": true,
        "children": []
        },
"2012": {
        "name": 2013,
        "ts_create": 1375254000000,
        "view_url": "some_url",
        "save_url": "some_url_2",
        "id": "",
        "exists": true,
        "children": []
        },
"2011": {
        "name": 2013,
        "ts_create": 1375254000000,
        "view_url": "some_url",
        "save_url": "some_url_2",
        "id": "",
        "exists": true,
        "children": []
        }
}

The problem I am facing is, it seems only in Google Chrome that when I loop over this object the objects loop backwards.

The expected result of looping over and displaying the object should list out things from 2013, 2012, 2011. Which happens in Firefox.. However no change in the method, same exact object in Chrome.. I will get 2011, 2012, 2013

So with this I need to obviously apply some level of sorting over this object before looping over it, seeing as Chrome wants to get the loop to read over it backwards. Problem I am facing with that is not entirely sure how to sort an object with JS

chris
  • 36,115
  • 52
  • 143
  • 252

4 Answers4

1

Instead of property/value pair implement this structure as an array of objects. Arrays you can sort by any property of objects it contains.

Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
1

Because objects are unordered collections, it's up to you to enforce the ordering you want.

One way is to get an Array of the object properties, sort them, then iterate the Array.

Object.keys(data)
      .sort(function(a, b) {
          return +b - +a;
       })
      .forEach(function(key) {
          var item = data[key];
      });

This assumes that you wanted a simple descending order.

1

When you iterate over object properties, there is no guarantee on the order. You can add your objects to an array, and sort the array instead:

var obj = {"2012" : {}, "2011" : {}, "2013" : {}};
var arr = [];
for (var year in obj) {
    arr.push({year : year, data : obj[year]});
}
arr.sort(function(a,b) {
    return b.year - a.year;
});

http://jsfiddle.net/wK5KE/

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
0

One way to get the keys in sorted order would be to use the method defined here to generate an array of the keys:

Getting JavaScript object key list

Then you could use the javascript sort function:

http://www.w3schools.com/jsref/jsref_sort.asp

Or write your own if you feel inclined.

Then just loop through the array of keys, using object[key] to extract the value.

Community
  • 1
  • 1