Iterate over jQuery JSON object in original order

前端 未结 4 1895
误落风尘
误落风尘 2021-01-04 09:13

I\'ve got some json data in a map object which is sorted by time. The key is an integer id and the value is an object which contains a timestamp. However when I try to ite

相关标签:
4条回答
  • 2021-01-04 09:24

    You could copy the key value pairs into an array of objects and then use Array.sort to put them in order.

    // $.getJSON(url, addPages); //removed for test purposes
    function addPages(pageData) {
        var pageItems = [];
        $.each(pageData, function(key,value){
            pageItems.push( { key: key, value: value } );
        });
        // Assuming you can do arithmetic on timestamps
        pageItems.sort( function(a,b){ return a.value.timeStamp - b.value.timeStamp; } ); 
        $.each(pageItems, function(index,pageItem){
            alert(pageItem.key+' : '+pageItem.value.timeStamp);
        });
    }
    

    My test script:

    var testData = { 
      '12': { timeStamp: 55 },
      '16': { timeStamp: 655 },
      '123': { timeStamp: 455 },
      '312': { timeStamp: 955 },
      '132': { timeStamp: 255 },
      '126': { timeStamp: 455 },
      '162': { timeStamp: 355 }
      };
    addPages(testData);
    
    0 讨论(0)
  • 2021-01-04 09:37

    In firefox objects keep the order.. in chrome they don't. No idea about other browser but two different implementations already show that you cannot rely on it.

    If you need something ordered, use a list; if you need something with both non-numeric keys and a certain order, the easiest way would be using a list of [key, value] lists:

    [['abd', 'def'], ['ghi', 'jkl']]
    
    0 讨论(0)
  • 2021-01-04 09:38

    If by "original" you mean the timestamp in the object, I don't think there's any foolproof option other than to first explicitly sort the array, and only then loop through it.

    0 讨论(0)
  • 2021-01-04 09:48

    Objects are un-ordered sets. You can't specify an order on them in a cross-browser complaint manner. There is no concept of original order unless it's already ordered by a rule.

    So sort the data on the server and then enumerate over it in the same sorted order.

    Alternatively format the JSON to be

    { "values": [
       { "someKey": "someVal" },
       { "someOtherKey": "someOtherVal" }
    ] }
    

    You can iterate over the array with a for (i = 0; i < len; i++) loop and "garantuee" the original order.

    0 讨论(0)
提交回复
热议问题