1

Let's say I want to declare an object bar and set it's values to be those of the object foo, but I'm uncertain whether foo will have all the requisite properties. I also want to preserve falsy values like "" from foo, rather than reverting to defaults. For example:

var foo = somefunc();
console.log(foo);
//{prop1: "", prop2: "works"}

var defaults = {prop1: "default1", prop2: "default2", prop3: "default3"}
/* some piece of code */
console.log(bar);
//should log: {prop1: "", prop2: "works", prop3: "default3"}

What would be the best /* some piece of code */ to use in Ecmascript 6 to initialize with defaults like this?

Duncan Marshall
  • 530
  • 1
  • 6
  • 15

4 Answers4

3

Is that works for you?

var foo = {prop1: "", prop2: "works"};
var defaults = {prop1: "default1", prop2: "default2", prop3: "default3"}
var bar = Object.assign({},defaults,foo)
console.log(bar); //{prop1: "", prop2: "works", prop3: "default3"}
  • 1
    Thanks! you can read more about Object.assign() [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) – Levi Berkowitz Feb 07 '20 at 10:22
3

You can elegantly use the spread operator to achieve this,

var foo = {prop1: "", prop2: "works"};
console.log(foo);

var defaults = {prop1: "default1", prop2: "default2", prop3: "default3"}
var bar = {...defaults, ...foo}
console.log(bar);
Saba
  • 3,418
  • 2
  • 21
  • 34
  • Are there reasons to favour this over `Object.assign` beyond the fact it's prettier? – Duncan Marshall Feb 07 '20 at 10:29
  • 1
    Good explanation provided here, https://stackoverflow.com/questions/32925460/object-spread-vs-object-assign – Saba Feb 07 '20 at 10:31
  • 1
    Might just be a case of not using the right terminology but note that object spread is not part of ES6. – Felix Kling Feb 07 '20 at 10:42
  • Partly not using the right terminology, in that I probably should have asked about "modern Javascript" rather than specifically Ecmascript6, but since it's standardized, this works nicely for my purposes at least. – Duncan Marshall Feb 07 '20 at 10:49
2

This can be done using Object.assign with an empty object as the target, and defaults and foo as the sources, in that order.

let bar = Object.assign({}, defaults, foo);
Jonas Høgh
  • 10,358
  • 1
  • 26
  • 46
2
var new_object={ ...defaults, ...foo }
Keith
  • 22,005
  • 2
  • 27
  • 44
dhamo
  • 545
  • 2
  • 7