是否可以在解构另一个对象时分配一个对象(WHILE使用解构中的默认值)

时间:2017-12-13 01:04:10

标签: javascript json ecmascript-next

我的最终目标是能够在分配默认值(如果它们不存在)的情况下,使用spread operator对象destructured分配新对象。

看起来我可能不喜欢这样。这是我的期望和尝试:



//Expected beginning object
const a1 = {
  key1: "test1",
  key2: "test2",
};

//Expected end result
const b1 = {
  key1: "test1",
  key2: "test2",
  key3: {
    nestedKey1: "nestedVal1",
  },
};

//Expected beginning object
const a2 = {
  key1: "test1",
  key2: "test2",
  key3: {
    nestedKey1: "actualValue",
  }
}

//Expected end result
const b2 = {
  key1: "test1",
  key2: "test2",
  key3: {
    nestedKey1: "actualValue",
  },
};




代码段1:不分配default值。



const a = {
  key1: "test1",
  key2: "test2",
}

const {...b} = {
  key1,
  key2,
  key3: {
    nestedKey1: nestedKey1 = "nestedVal1",
  } = {},
  key4 = 'someDefault'
} = a

console.log(b); // does not have key3, or key4
console.log(key4); //this exists as a const, key3 does not




Snippet 2:功能齐全,但如果需要多级嵌套,则可能会出现问题。



const a = {
  key1: "test1",
  key2: "test2",
}

let {
  key1,
  key2,
  key3: {
    nestedKey1: nestedKey1 = "nestedVal1",
  } = {},
} = a

const key3 = a.key3 || {}; // is it possible to include this in the destructuring? Specifically in the destructuring which defines the default.

const b = {
  key1,
  key2,
  key3: {
    ...key3,
    nestedKey1,
  }
}

console.log(b);




小部件2(显示嵌套对象未被覆盖)



const a = {
  key1: "test1",
  key2: "test2",
  key3: {
    someOtherKey: "itWorks",
  }
}

let {
  key1,
  key2,
  key3: {
    nestedKey1: nestedKey1 = "nestedVal1",
  } = {},
} = a

const key3 = a.key3 || {};

const b2 = {
  key1,
  key2,
  key3: {
    ...key3,
    nestedKey1,
  }
}

console.log(b2);




1 个答案:

答案 0 :(得分:1)

您的困惑来自解构语法与对象声明语法的相似性。

这是对象声明:

const a = {
  key1: "test1",
  key2: "test2",
}

这是破坏性的

const { key1, key2 } = a

console.log(key1)  // => test1
console.log(key2)  // => test2

接下来,您需要记住赋值运算符=在JavaScript中是正确的关联。像

let a = b = 1

是指将值1分配给b,然后分配给a

接下来,如果将所有值都分散到一个var中,则实际上是在使用花哨的ES6语法进行简单分配。所以:

const {...b} = a
// is same as
const b = a

结合以上3种效果,您得到的实际上是多次分配:

const {...b} = a  
const {key1, key2} = a

多次分配可能会造成混淆,并且存在禁止使用此类规则的规则:https://eslint.org/docs/rules/no-multi-assign

所以您的问题的答案很简单,不! :)

这样做至少需要两行-一个用于在销毁时收集具有默认值的道具,另一个用于使用这些道具创建下一个对象。