0

Lets say I have this simple object:

var User = {
    name: 'Hans',
    get_name: function(){return this.name},

    street: 'Kings',
    postcode: '482932',
    city: 'New York'
}

For a better overview, I would like to do something like this:

var User = {
    name: 'Hans',
    get_name: function(){return this.name},
};

//Adress Information
User.add({
    street: 'Kings',
    postcode: '482932',
    city: 'New York'
});

As expected this doesn´t work. To achieve somthing similar I could write:

User.street = 'Kings';
User.postcode = '482932';
.......

But I would like to add several attributes at the same time. Is there a handy function for it? Thanks

John Smith
  • 6,105
  • 16
  • 58
  • 109

2 Answers2

1

Using ES6 (this will overwrite existing properties):

Object.assign(User, { /* some new props */ });

Using lodash (this won't overwrite existing properties):

_.extend(User, { /* some new props */ });

In ES5 by adding a method to User:

User.add = function(newProps) {
  Object.keys(newProps).forEach(function(prop) {
    this[prop] = newProps[prop];
  }.bind(this));
};

Really, the add method should go in the User.prototype if you want to follow OO "principles".

Josh Beam
  • 19,292
  • 3
  • 45
  • 68
  • Thanks @JoshBeam `Object.assign`, really will help me to keep my code clean! – John Smith Oct 12 '15 at 20:30
  • @JohnSmith, no problem. Keep in mind, it's an ECMAScript6 method, so you'll need an environment that supports it (such as Node harmony, or by using something like Babel to compile ES6 into ES5) – Josh Beam Oct 12 '15 at 20:33
1

One solution :

var User = {
    name: 'Hans',
    get_name: function(){return this.name},
};
User.add = function(obj){
  var me = this;
  Object.keys(obj).forEach(function(o){
    if(! me[o] ) me[o] = obj[o];
  })
}
//Adress Information
User.add({
    street: 'Kings',
    postcode: '482932',
    city: 'New York'
});

console.dir(User)
/*
    name        "Hans"
    get_name    function()
    add         function(obj)
    street      "Kings"
    postcode    "482932"
    city        "New York"
*/

    var User = {
        name: 'Hans',
        get_name: function(){return this.name},
    };

    User.add = function(obj){
      var me = this;
      Object.keys(obj).forEach(function(o){
        if(! me[o] ) me[o] = obj[o];
      })
      return this;
    }
    //Adress Information
    User.add({
        street: 'Kings',
        postcode: '482932',
        city: 'New York'
    });

    console.dir(User);
    /*
        name        "Hans"
        get_name    function()
        add         function(obj)
        street      "Kings"
        postcode    "482932"
        city        "New York"
    */

    document.getElementById('el').innerHTML = '<pre>'+JSON.stringify(User , null , ' ')+'</pre>';
<div id='el'><div>
Anonymous0day
  • 3,012
  • 1
  • 14
  • 16