reverse json javascript
Is there an inexpensive way to reverse:
{
"10": "..."
"11": "...",
"12": "...",
"13": "...",
"14": "...",
}
so that I get:
{
"14": "...",
"13": "...",
"12": "..."
"11": "...",
"10": "...",
}
reverse() doesn't seem to work on json objects. The only way I can think of is to loop through all the elements and create an array. feels like there should be a better way.
Edit: thanks for all the help UPDATE:
What about let's say if each key has chronological data. When I use $.each on the object, it runs through the objects from top to bottom, I didn't realize that was unreliable.
Here's what I'm trying to do:
$.ea开发者_如何学编程ch(object, function (key, value) {
function foo (key, value);
});
I want to not run foo on all but the last 3 pairs, that is I only want to use the last 3 pairs. I figured if I can reverse them I can just run the first three and stop.
Is there any way I can just do the last 3? If the last 3 ordering is unreliable, is there a safer way to grab the last 3. The last 3 will have the largest numerical keys.
Thanks.
Edit 2: I'm basically deciding finally to do the manipulations on the server side. I'm reorganizing my database so that the relevant subdocuments are now full on documents that could be queried with mongodb. Thanks.
Javascript associative arrays are unordered. You cannot depend on the properties being in any particular order.
From Mozilla Developer Network:
Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. In Explorer, while the property value is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its old position--not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.
So if you want to simulate an ordered associative array in a cross-browser environment, you are forced to either use two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.
Use this on json objects arrays
jsonObjectArray.reverse();
$.each(jsonObjectArray, function(i, item) {
//do something with the item
});
Hope this helps
This might help. Get all the keys from the json objects into an array, which you can sort.
var a = { 1 : 'x', 3 : 'y', 2 : 'z' };
var keys = []
for (i in a) { keys.push(i); }
keys.sort();
then you can use reverse() and slice() to just iterate over the keys you need.
$.each(keys, function(idx, key) {
// do whatever with a[key]
});
Follow the json in reverse order,
for(json.length;i>=0;i--)
{
console.log(json.[i]);
}
精彩评论