Aviv Cohn
Aviv Cohn

Reputation: 17193

How can I set default values for an object's keys?

A function receives an object o. The function requires it has four keys, a, b, c, d. For each one that is undefined, we want to set a custom default value. One option would be:

function func(o) {
    o.a = o.a || 12;
    o.b = o.b || function() {}
    // and so on
}

But is there a more elegant or idiomatic option?

Upvotes: 1

Views: 52

Answers (1)

Oriol
Oriol

Reputation: 288130

Note your approach will overwrite falsy values different than undefined, like 0, "", NaN, false.

Assuming you only want the enumerable own properties of o, you can use Object.assign:

function func(o) {
  o = Object.assign({
    a: 12,
    b: function() {}
  }, o);
}

Basically, it creates a new object with the default values, and overwrites it with the data from the argument.

Upvotes: 3

Related Questions