javascript 按原始顺序迭代 jQuery JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4857666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:07:30  来源:igfitidea点击:

Iterate over jQuery JSON object in original order

javascriptjqueryjson

提问by Doug

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 iterate over this data with the jQuery $.each function, the results come back sorted by the key instead. How can I iterate over my collection of objects in their original order?

我在按时间排序的地图对象中有一些 json 数据。键是一个整数 id,值是一个包含时间戳的对象。但是,当我尝试使用 jQuery $.each 函数迭代此数据时,结果返回按键排序。如何按原始顺序迭代我的对象集合?

Code example:

代码示例:

$.getJSON(url, addPages);
function addPages(pageData) {
    $.each(pageData, function(key,value){
        alert(key+' : '+value);
    }
}

采纳答案by Noel Walters

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

您可以将键值对复制到一个对象数组中,然后使用 Array.sort 将它们排序。

// $.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);

回答by Raynos

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

或者将 JSON 格式化为

{ "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.

您可以使用循环遍历数组for (i = 0; i < len; i++)并“保证”原始顺序。

回答by ThiefMaster

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.

在 Firefox 对象中保持顺序.. 在 chrome 中他们没有。不知道其他浏览器,但两种不同的实现已经表明您不能依赖它。

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:

如果您需要订购某些东西,请使用列表;如果您需要具有非数字键和特定顺序的东西,最简单的方法是使用 [key, value] 列表的列表:

[['abd', 'def'], ['ghi', 'jkl']]

回答by sdleihssirhc

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.

如果“原始”是指对象中的时间戳,我认为除了首先对数组进行显式排序,然后再循环遍历之外,没有任何万无一失的选项。