是否可以将对象分解为现有变量?

时间:2019-12-19 20:00:29

标签: javascript ecmascript-6 destructuring object-destructuring

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

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
}

3 个答案:

答案 0 :(得分:2)

在这里可以这样做。

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);

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

对我想做的事情还不是100%清楚。

如果要使用point的两个属性更新complexPoint

您实际上可以将对象分解为任何可分配的对象。通常,您会将其分解为变量,但也可以将其分解为 properties

示例:

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');