I have a global JavaScript object with multiple properties and functions that I am creating it this way:
myObject = {};
I thought that I can ea
Without jQuery, you could create an array of objects with something like this:
[{'key': 'atuhoetu', 'value': 'uehtnehatn'},{...}]
If you don't care about compatibility, recent browsers should support this:
var newObj = {prop1: 'val', prop2: 'val'};
Object.keys(newObj).forEach(function (item) {
myObject[item] = newObj[item];
});
This will iterate over all items in newObject and add them to myObj.
Or, something cleaner:
function extend(target, source){
for(prop in source){
target[prop] = source[prop];
}
}
If you use it the following way:
var objA = {a: "a"};
var objB = {b: "b", c: "c"};
extend(objA, objB);
The result will be:
objA = {a: "a", b: "b", c: "c"};
When you write myObject = { ... }
, you're creating a brand-new object and setting myObject
to point to it.
The previous value of myObject
is thrown away.
Instead, you can use jQuery:
jQuery.extend(myObject, { newProperty: whatever });