I am trying to extend an Object of the following structure (with JQuery in Coffeescript):
objectThatIsAList = {
'List Item' :
callback :=>
return "Some value"
'Another item' :
callback :=>
return "Another value"
'The final item' :
callback :=>
no
}
This Object is used as a (dynamic) model for a dropdown menu in a large coffeescript-based framework.
I am extending it with
objectThatIsAList = $.extend {}, objectThatIsAList, {
'New Item' :
callback :=>
return "New stuff"
}
This results in an Object like this (comments added to show intended outcome)
objectThatIsAList = {
'List Item' :
callback :=>
return "Some value"
'Another item' :
callback :=>
return "Another value"
# this should be last
'The final item' :
callback :=>
no
# this should not be last
'New Item' :
callback :=>
return "New stuff"
}
Obviously, the object gets extended correctly, however the order of properties is relevant for the purpose of building a list. I'd much rather want the 'Final Item'
as the fourth and not the third property of the extended Object.
But my research did not show indexing support for the $.extend
method. Has anyone successfully implemented such a feature and/or has tips how to go about 'inserting' object properties into another object at a certain position?
Or is there a clever way to reposition that final item after the $.extend
?
Does not necessarily have to be Coffee, even JS or Pseudocode would be of great help.
EDIT:
This is the solution that i have come up with that extends the legacy code to take arrays and convert them to objects (that are being used extensively all over the framework and where changing the original code would break alot of working code):
# this comparison yields a data object that is passed to a method rendering a menu
if o.menu instanceof Array
menuArrayToObj = {}
for menuObject in o.menu
for menuObjectProperty,menuObjectValue of menuObject
menuArrayToObj[menuObjectProperty]=menuObjectValue if menuObjectProperty? and menuObjectValue?
o.menu = menuArrayToObj
else o.menu
With this in place, it can either be fed an object or a array. The latter is easily inserted into with splice.
Javascript objects are by definition unordered.
If you wish to maintain an ordering you need an Array
instead.
A good example of this is the jQueryUI dialog object. Although it's possible to use an Object
in the way you have for the buttons
option, if you require the individual buttons to be in a specific order then you have to supply an array of objects.
Using this model, your object would look like:
arrayThatIsAList = [
{ title: 'List Item', callback: ... },
{ title: 'Another Item', callback: ... },
{ title: 'New Item', callback: ... },
{ title: 'The final item', callback: ... }
];