I have a JavaScript object written in javascript code as below:
var rtnStr = {\"000\":\"area000\",\"020\":\"area020\",\"030\":\"area030\",
\"040\":
var rtnStr = {"000":"area000","020":"area020","030":"area030",
"040":"area040","047":"area047","049":"area049",
"050":"area050","060":"area060","070":"area070",
"100":"area100", "900":"area900"};
array_ = [];
for (var key in rtnStr) {
array_.push(key)
}
array_.sort();
for (var key in array_) {
document.write('rtnStr[' + key + ']= ' + rtnStr[key] + '<br />');
}
As mentioned by @Quentin, the order of the properties in JavaScript objects is undefined. The spec doesn't even mention if the properties will be returned in the same order by different for..in
s.
What you can do is get the keys in an array and sort them:
var rtnStr = {"000":"area000","020":"area020","030":"area030",
"040":"area040","047":"area047","049":"area049",
"050":"area050","060":"area060","070":"area070",
"100":"area100", "900":"area900"};
var keys = Object.keys(rtnStr).sort().forEach(function(key){
document.write('rtnStr[' + key + ']= ' + rtnStr[key] + '<br />');
});
MDN has a page for Object.keys where you can find the browsers it works on and a polyfill for those it doesn't.
One thing to note is that your initial version of the code iterates over inherited properties as well. That is generally considered to be unsafe and Object.keys
doesn't exhibit that behavior.
JavaScript objects are unordered.
If you want to output their properties in a sorted order then: