What I am looking for is to be able to add to an object, but not to do something like messageStrings.x = 1 for each one.
For example, in one file we may have something like:
var messageStrings = {
Edit: "Edit",
Cancel: "Cancel"
}
and another file, want to add more to the object:
var messageStrings = {
Update: "Update",
Save: "Save"
}
What is the best way of doing a bulk add to an existing object?
Thanks.
Many libraries provide an "extend" function, which lets you do something like this:
var obj = extend({ "default": "something"}, { "more": "stuff", "even": "more" });
which would give you an object with properties "default", "more", and "even."
What the function looks like is this:
function extend() {
var args = Array.prototype.slice.call(arguments, 0);
var target = args[0];
for (var i = 1; i < args.length; ++i) {
for (var k in args[i]) {
target[k] = args[i][k];
}
}
return target;
}
Some implementations might have slightly varying semantics, such as whether to always return a result that's a freshly-minted object, or instead to always modify the first parameter like that one does.
Note also that that's a shallow copy — to make a complete "deep" copy, you'd need more code.
You can do this in typescript:
var messageStrings = {
Edit: "Edit",
Cancel: "Cancel"
}
var messageString2 = {
Update: "Update",
Save: "Save"
}
let obj = {...messageStrings, ...messageString2}
it will give you:
{Edit: "Edit", Cancel: "Cancel", Update: "Update", Save: "Save"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With