In my Javascript application I have an Object and I need to be able to order the array by a value within the Inner Object.
For example:
{
a : {
timestamp: xxxxxx
other : yyyyyy
},
b : {
timestamp: xxxxxx
other : yyyyyy
},
c : {
timestamp: xxxxxx
other : yyyyyy
}
}
What I need to do is manage this data set and re-order the array according to the timestamp of each inner object.
What ways are they that I can do to do this?
update:
My initial thought would be doing something like so:
{
a : {},
b : {},
c : {},
_ : [
c, a, b //Key's Only
]
}
Then re-indexing the the object based on those values, that would sort out how to index the object, but when I insert a new element i would also have to regenerate the _
index relationship which seems way to much effort.
You can copy the data to an array and then sort it:
var data = {
a : {
timestamp: 11111,
other : "xxx"
},
b : {
timestamp: 22222,
other : "yyy"
},
c : {
timestamp: 33333,
other : "zzz"
}
};
var output = [];
// copy items to an array so they can be sorted
for (var key in data) {
data[key].key = key; // save key so you can access it from the array (will modify original data)
output.push(data[key]);
}
output.sort(function(a,b) {
return(a.timestamp - b.timestamp);
});
Generates this as output (note I added the original key to the object so it's accessible from the array):
[{"timestamp":11111,"other":"xxx","key":"a"},
{"timestamp":22222,"other":"yyy","key":"b"},
{"timestamp":33333,"other":"zzz","key":"c"}]
You can see this working here: http://jsfiddle.net/jfriend00/hXpkP/
Javascript objects are not associative arrays. They may behave similarly, but they are not the same. Javascript has no associative arrays.
While associative arrays have a concept of order, Javascript objects simply do not share this particular feature with them. Objects, by there very nature, are not ordered.
So, to answer your question: you cannot order them...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With