【问题标题】:Is it possible to destructure an object into existing variables?是否可以将对象解构为现有变量?
【发布时间】:2020-04-12 10:24:08
【问题描述】:

我正在尝试使用对象解构来提取变量,但这些变量已经存在,就像这样

const x=1, y=2 // Those should be 1 and 2
const {x,y} = complexPoint
const point = {x,y}

有没有办法在不重命名解构变量的情况下做到这一点? 一些喜欢这样的更新点避免const定义?

const point = {x,y} = complexPoint

预期的结果应该是使用对象解构

const x=1, y=2 // Those should be 1 and 2
const point = {
  x:complexPoint.x,
  y:complexPoint.y
}

【问题讨论】:

  • 不确定你想在那里实现什么。您是否尝试通过解构提取然后创建对象?
  • 是的,我正在尝试仅提取这些变量
  • 复点的内容是什么?
  • 它是一个像{x,y,z,w,otherFunctions ....}这样的大复杂对象

标签: javascript ecmascript-6 destructuring object-destructuring


【解决方案1】:

这里可以这样。

const complexPoint = {x: 1, y: 2, z: 3};
const simplePoint = ({x, y}) => ({x, y});

const point = simplePoint(complexPoint);

console.log(point);

在一行中看起来像这样:

const complexPoint = {x: 1, y: 2, z: 3};

// can be written as
const point2 = (({x, y}) => ({x, y}))(complexPoint);

console.log(point2);

【讨论】:

    【解决方案2】:

    您可以通过数组解构来做到这一点,即:

    const complexPoint = [1,2];
    
    let x, y;
    [x,y] = complexPoint;
    

    至于对象解构,等效的语法不会起作用,因为它会抛出解释器:

    const complexPoint = {x:1,y:2};
    
    let x, y;
    {x,y} = complexPoint; // THIS WOULD NOT WORK
    

    解决方法可能是:

    const complexPoint = {x:1,y:2};
    
    let x, y;
    [x,y] = [complexPoint.x, complexPoint.y];
    
    // Or
    [x,y] = Object.values(complexPoint);
    

    更新:

    看来您可以通过将赋值括在括号中并将其转换为表达式来将对象解构为现有变量。所以这应该有效:

    const complexPoint = {x:1,y:2};
    
    let x, y;
    ({x,y} = complexPoint); // THIS WILL WORK
    

    【讨论】:

    • 错了。将对象解构为变量确实有效(在表达式上下文中)!
    • 思路是不要修改x和y
    • @JonasWilms 你能举个例子说明你的意思吗?
    • 其实你是对的。如果将赋值括在括号中,则可以将对象解构为现有变量。即 ({x,y} = complexPoint)
    • 注意; 在括号前的那一行是必需的(这里所有行都有;,所以这很好)
    【解决方案3】:

    我不是 100% 清楚你想做什么。

    如果你想用complexPoint的两个属性更新point

    您实际上可以将对象解构为任何可分配的对象。大多数情况下,您将解构为变量,但您也可以解构为属性

    例子:

    const point = {x: 1, y: 2};
    const otherPoint = {x:3, y: 4};
    
       ({x: point.x, y: point.y} = otherPoint);
    // ^                                     ^
    // parenthesis are necessary otherwise the runtime will interpret {
    // as the start of a block
    
    console.log(point);

    当然,您拥有的属性越多,阅读起来就越困难。您也可以直接分配它们,这是老式的好方法:

    point.x = otherPoint.x;
    point.y = otherPoint.y;
    

    或者使用循环:

    for (const prop of ['x','y']) {
      point[prop] = otherPoint[prop];
    }
    

    如果您想从现有对象创建新对象

    创建一个辅助函数来“挑选”现有对象的属性。 here提供了这样的功能。

    const point = pick(otherPoint, 'x', 'y');
    

    【讨论】:

      猜你喜欢
      • 2019-10-28
      • 2015-06-19
      • 1970-01-01
      • 2017-08-22
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      • 2020-04-26
      相关资源
      最近更新 更多