用Ecmascript 6中省略值的默认值初始化对象的最佳方法是什么?

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?

评论
  • qodio
    qodio 回复

    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);
    
  • 如果他
    如果他 回复

    那对你有用吗?

    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的唯一
    唯1的唯一 回复

    var new_object = {...默认值,... foo}