简体   繁体   中英

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. I know you can rename an object like this:

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.

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

 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. Check it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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