Search code examples
javascriptobject-literal

Short-hand to add many key/value pairs to an existing JavaScript object?


If I have an existing POJO and want to add some key/value pairs to it, I normally do it like so:

var existingObject = {
    firstValue: 'hello'
};

/* some time later... */

existingObject.secondValue = 'world';
existingObject.thirdValue = 'new value';
existingObject.fourthValue = 'another value';
existingObject.fifthValue = 'another value';
existingObject.sixthValue = 'another value';
existingObject.seventhValue = 'another value';
existingObject.eighthValue = 'another value';
existingObject.adInfinitum = 'again and again...';

But I wonder if there is a more efficient way than this longhanded approach? Note however, that I am looking for alternatives to creating a temp object and calling extend.

Also, simply storing the object in a smaller variable (like var a = existingObject; and using a.newValue = 'something') isn't a solution I am looking for.

Is there a way to do this?


Solution

  • With the new ES6 method Object.assign, much of the repeated boilerplate can be eliminated. Example:

    var existingObject = {
        firstValue: 'hello'
    };
    
    /* some time later... */
    
    Object.assign(existingObject, {
      secondValue: 'world',
      thirdValue: 'new value',
      fourthValue: 'another value',
      fifthValue: 'another value',
      sixthValue: 'another value',
      seventhValue: 'another value',
      eighthValue: 'another value',
      adInfinitum: 'again and again...'
    });
    // existingObject now has all these properties
    

    This will do it without using other temporary variables or calling some external extend method.