Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bulk Adding To Javascript Object

Tags:

javascript

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.

like image 563
fanfavorite Avatar asked Oct 27 '25 08:10

fanfavorite


2 Answers

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.

like image 72
Pointy Avatar answered Oct 29 '25 23:10

Pointy


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"}
like image 41
Lilian Bideau Avatar answered Oct 29 '25 23:10

Lilian Bideau