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 开发者_如何学C= {
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 are using jQuery you can extend an object in this way:
$.extend(objectA, objectB);
In this way you will get an object containing both A and B properties.
Otherwise you can use a simple for in loop like:
for (var x in obj2) {
obj1[x] = obj2[x];
}
This is of course a mere example, you should do some check to avoid data overwriting
You could merge new values into the existing object.
jQuery has extend
method for this.
If jQuery is not an option, you can write up a simple recursive contraption (probably checking hasOwnProperty
just in case some library littered Object.prototype
).
精彩评论