It feels hacky to me, but parseInt on the key should work. sort could sort if IE support isn’t needed. It might be possible to sort by keys without the parseInt. Worth giving it a try.
Thanks. But I would not like to use sort function because this will sort the values. In some cases I may have a requirement that I would need to display it in the following order:
var obj = {
"1st":"1",
"4th":"4",
"2nd":"2",
"3rd":"3",
"5th":"5"
};
So, I was wondering if it’s possible to manualy set the order?
Properties in objects are an unordered collection. You could push your object into a Map object, which does guarantee the order of elements.
Your alternative is to manually create an array of the keys you want to access in order… ["1st","5th","4th","2nd","3rd"].forEach(function (x) { console.log(obj[x]); });
I created manual array as shown in the JSFiddle here
var obj = {
"1st":"1",
"2nd":"2",
"4th":"4",
"3rd":"3",
"5th":"5"
};
console.log(obj);
var patArray = new Array();
patArray.push(obj["1st"]);
patArray.push(obj["2nd"]);
patArray.push(obj["3rd"]);
patArray.push(obj["4th"]);
patArray.push(obj["5th"]);
for (var i in patArray) {
console.log(patArray[i]);
}
So, it prints in the order I want but, say for example, in future , dynamically, one of the value is deleted from the database or added in my object(by adding it in database) then this could create problem, right?
Yes, but if you cant programmatically describe the order you want an unspecified set of keys to be output in, then you will always have that problem.
Responsive code will always need an algorithm to follow. “Alphabetical order” is .sort’s default algorithm, so it can handle any values you throw at it.