简体   繁体   English

用符号或数字重命名 object 键解构

[英]Renaming object keys destructuring with a symbol or a number

I was just wondering if there is a way to rename object key values with a symbol or a number as the new name.我只是想知道是否有办法用符号或数字作为新名称重命名 object 键值。 I know you can rename an object like this:我知道您可以像这样重命名 object:

let totalValues = {3V: 2.09, fg%V: 3.02}
const {'3V': threev, 'fg%V': fgV } = totalValues;
totalValues = {threev, fgV };

is there a way to rename the values like this with it working?有没有办法在它工作的情况下重命名这样的值?

let totalValues = {3V: 2.09, fg%V}
const {'3V': 3PM, 'fg%V': FG%} = totalValues;
totalValues = {3PM, FG%};

% is an invalid symbol when declaring a variable name, however it is legal in JSON object naming. %在声明变量名时是无效符号,但在 JSON object 命名中是合法的。

You can rename and deconstruct like this, so long as the variable you are renaming to is legal.你可以像这样重命名和解构,只要你重命名的变量是合法的。

Numbers are valid in variables, as long as the are accompanied by a non-numeric value.数字在变量中是有效的,只要伴随着一个非数字值。

let totalValues = {'3V': 2.09, 'fg%V': 3.02};
let { 'fg%V': fgv } = totalValues;
console.log(fgv); // 3.02

Happy Coding!快乐编码!

You can create object like from:to name您可以创建 object 像from:to name

 const totalValues = { '3V': 2.09, 'fg%V': 3.02, do_not_rename: 1 }; const renameFromTo = { '3V': '3PM', 'fg%V': 'FG%', }; const result = Object.entries(renameFromTo).reduce( (acc, [from, to]) => ({...acc, [from]: undefined, [to]: acc[from] }), totalValues, ); console.log(result);

In javaScirpt naming variables has specific rules, you can't start a variable name with a number or use special character except _ , so while destructing you are actually creating variables so you must follow the rules.在 javaScirpt 中命名变量有特定的规则,你不能以数字开头变量名或使用除_之外的特殊字符,所以在破坏时你实际上是在创建变量,所以你必须遵守规则。 Check it 核实

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM