解构ES6嵌套对象

Destructuring ES6 Nested Objects

本文关键字:对象 嵌套 ES6 解构      更新时间:2023-09-26

我如何使用ES6与解构提供选项给用户。不确定如何使用嵌套对象而不被部分对象覆盖默认值。

以MDN中的这个简单示例为例:

function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {})
{
  console.log(size, cords, radius);
  // do some chart drawing
}
drawES6Chart({
  cords: { x: 18},
  radius: 30
});

输出显示

big {"x":18} 30

但是我想让它显示

big {"x":18,"y": 0} 30

提供的cord对象是局部的,并删除默认的y值。

您需要将coords分解为其xy组件,并分别为它们提供默认值:

function drawES6Chart({size='big', cords: {x=0, y=0} = {}, radius=25} = {}) {
    const coords = {x, y}
    console.log(size, coords, radius);
}

如果根本没有提供cords对象,您编写它的方式将只提供默认值。
您已经为完整的选项对象选择了正确的方法,它也将{}作为其默认值—而不是写入

function drawES6Chart({size, cords, radius} = {size:'big', cords:{x:0, y:0}, radius:25}) {
    // not working

您可以为整个选项对象提供默认值(就像您一样),但不能(直接)为其中的从属对象提供默认值。

我喜欢bergi的回答,但是正如Paul指出的,它确实定义了函数中的xy符号。

如果你不想这样做,你可以在函数中使用Object.assign:

cords = Object.assign({}, {x: 0, y:0}, cords);

感觉有点es5,但是…

为了避免重复,你可以把默认值放在一个变量中:(Babel的REPL上的live copy)

let cordsDefaults = {x: 0, y: 0};
function drawES6Chart(
  {size = 'big', cords = cordsDefaults, radius = 25} = {}
  )
{
  cords = Object.assign({}, cordsDefaults, cords);
  console.log(size, cords, radius);
  // do some chart drawing
}
drawES6Chart({cords: {x:18}});
输出:

<>之前大{"x":18,"y":0