Bryce
Bryce

Reputation: 6610

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?

Upvotes: 1

Views: 3539

Answers (2)

Bryce
Bryce

Reputation: 6610

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.

Upvotes: 13

Jeffrey Drake
Jeffrey Drake

Reputation: 815

Short answer: no.

Alternatively, the best I can suggest, is a function that takes variable arguments, alternating between keys and values. Just make it a bare function, optionally taking an existing object to extend.

Upvotes: 3

Related Questions