如何在ES6中将结构化为动态命名的变量? [英] How to destructure into dynamically named variables in ES6?

查看:520
本文介绍了如何在ES6中将结构化为动态命名的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下对象:

const user = { 
  id: 42, 
  displayName: "jdoe",
  fullName: { 
      firstName: "John",
      lastName: "Doe"
  }
};

我只想要 id fullName

我将执行以下操作:

const { id, fullName } = user

Easy-peasy ,对吗?

Easy-peasy, right?

现在让我们假设我想根据另一个名为字段的变量的值进行解构。

Now let's suppose that I want to do the destructuring based on the value of another variable called fields.

const fields = [ 'id', 'fullName' ]

现在我的问题是:如何根据一系列密钥进行解构?

我无耻地尝试以下方法但没有成功:

I shamelessly tried the following without success:

让{[{... fields}]} = user 让{[... fields]} =用户。有没有办法可以做到这一点?

let {[{...fields}]} = user and let {[...fields]} = user. Is there any way that this could be done?

谢谢

推荐答案

使用动态密钥进行结构化并非不可能。为了防止创建动态变量的问题(如Ginden所提到的),您需要提供别名。

It's not impossible to destructure with a dynamic key. To prevent the problem of creating dynamic variables (as Ginden mentioned) you need to provide aliases.

const user = { 
  id: 42, 
  displayName: "jdoe",
  fullName: { 
      firstName: "John",
      lastName: "Doe"
  }
};

const fields = [ 'id', 'fullName' ];
const object = {};

const {[fields[0]]: id, [fields[1]]: fullName} = user;

console.log(id); // 42
console.log(fullName); // { firstName: "John", lastName: "Doe" }

解决问题必须为动态值定义静态别名,您可以分配给对象的动态属性。在这个简单的例子中,这与恢复整个解构相同,但是:)

To get around the problem of having to define static aliases for dynamic values, you can assign to an object's dynamic properties. In this simple example, this is the same as reverting the whole destructuring, though :)

const user = { 
  id: 42, 
  displayName: "jdoe",
  fullName: { 
      firstName: "John",
      lastName: "Doe"
  }
};

const fields = [ 'id', 'fullName' ];
const object = {};

({[fields[0]]: object[fields[0]], [fields[1]]: object[fields[1]]} = user);

console.log(object.id); // 42
console.log(object.fullName); // { firstName: "John", lastName: "Doe" }

来源:

https://github.com/getify/You-Dont-Know-JS/ blob / master / es6%20%26%20beyond / ch2.md#not-just-declarations

这篇关于如何在ES6中将结构化为动态命名的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆