Ever thought about creating your own custom list constructor?
function CustomList(obj) {
if (this instanceof CustomList) {
var instance = this,
keysArray = [];
/* Initialize: add the properties of [obj] to the list,
and store the keys of [obj] in the private keys array */
for (var prop in obj) {
keysArray.push(prop);
instance[prop] = obj[prop];
}
/* Public:
Add a property to the list
*/
instance.add =
function(key, value) {
instance[key] = value;
keysArray.push(key);
return instance; /* Allows method chaining */
};
/* Public:
Return raw or sorted list as a string, separated by [separator]
Without [sort], the order of properties is maintained based on
the order in which they were added to the list
*/
instance.iterate =
function(sort, separator){
separator = separator || '\n';
var resultArr = [],
sortedKeys = sort ? keysArray.slice().sort() : keysArray;
for (var i = 0; i < sortedKeys.length; i++){
resultArr.push(sortedKeys[i] + ': ' + instance[sortedKeys[i]]);
}
return resultArr.join(separator);
};
} else if (obj && obj instanceof Object) {
return new CustomList(obj);
} else if (arguments.length === 2) {
var newObj = {};
newObj[String(arguments[0])] = arguments[1];
return new CustomList(newObj);
} else { return true; }
/* The 'if (this instanceof List)' pattern makes
the use of the 'new' operator unnecessary. The
constructor also allows initialization with
2 parameters => 'CustomList(key,value)'
*/
}
You can now view the raw list (maintains the order properties were added) or a sorted list:
var myList =
CustomList( { 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
*/