How about cooking your own list constructor?
function List(obj) {
if (this instanceof List) {
var t = this,
keys = [];
/* inititalize: add the properties of [obj] to the list,
and store the keys of [obj] in the private keys array */
for (var l in obj) {
keys.push(l);
t[l] = obj[l];
}
/* public:
add a property to the list
*/
t.add =
function(key, value) {
t[key] = value;
keys.push(key);
return t; /* allows method chaining */
};
/* public:
return raw or sorted list as string, separated by [separator]
Without [sort] the order of properties is the order in which
the properties are added to the list
*/
t.iterate =
function(sort,separator){
separator = separator || '\n';
var ret = [],
lkeys = sort ? keys.slice().sort() : keys;
for (var i=0;i<lkeys.length;i++){
ret.push(lkeys[i]+': '+t[lkeys[i]]);
}
return ret.join(separator);
};
} else if (obj && obj instanceof Object) {
return new List(obj);
} else if (arguments.length === 2) {
var a = {};
a[String(arguments[0])] = arguments[1];
return new List(a);
} else { return true; }
/* the 'if (this instanceof List)' pattern makes
the use of the 'new' operator obsolete. The
constructor also allows to be initialized with
2 parameters => 'List(key,value)'
*/
}
now you can have it raw (the order you added props is maintained) or sorted:
var myList =
List( { orange:123,
banana:4,
apple:567 }
);
myList.add('peach',786);
alert(myList.iterate());
/*=>output:
orange: 123
banana: 4
apple: 567
peach: 786
*/
or: alert(myList.iterate(1));
/*=>output:
apple: 567
banana: 4
orange: 123
peach: 786
*/