ES6/ES2015 object destructuring and changing target variable
You can assign new variable names, like shown in this MDN Example
var o = { p: 42, q: true };
// Assign new variable namesvar { p: foo, q: bar } = o;
console.log(foo); // 42console.log(bar); // true
Destructuring and rename property
You could destructure with a renaming and take the same property for destructuring.
const a = { b: { c: 'Hi!' } };const { b: formerB, b: { c } } = a;
console.log(formerB)console.log(c);
Object destructuring with property names that are not valid variable names
You can assign it a valid variable name using this syntax:
var {"my name": myName, age} = obj2;
// use myName here
Why isnt this object destructuring working?
You need to use name
and age
as the variables that you destructure from the object like so:
let obj={age: "3", name: "spike"};let {age, name}=obj;
console.log(age);console.log(name);
Rename object keys of return object
Just use different variable names:
const { content, data } = matter(source1)
const { content: content2, data: data2 } = matter(source2)
Or don't destructure at all:
const result1 = matter(source1)
const result2 = matter(source2)
Or use an array of objects:
const results = [source1, source2].map(matter);
TypeScript imports vs. ES6 object destructuring
Use the solution suggested by Jaromanda X:
const {longVarName: lvn} = x.bar;
In fact, you can do more than that:
Multiple variables
var {p: foo, q: bar} = o;
Default values:
var {a = 10, b = 5} = {a: 3};
Nested objects:
const x = {a: {b: {c: 10}}};
const {a: {b: {c: ten}}} = x;
// ten === 10
For more info, see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Related Topics
How to Detect in iOS Webapp When Switching Back to Safari from Background
How Does Linux Emulator in JavaScript by Fabrice Bellard Work
JavaScript Equivalent of Ruby's String#Scan
What Blocks Ruby, Python to Get JavaScript V8 Speed
Is Ruby Strongly or Weakly Typed
Regex Match Count of Characters That Are Separated by Non-Matching Characters
Parsing JavaScript Using Ruby Code
How to Use .Env Variables in Nuxt 2 or 3
Is There a Link to the "Latest" Jquery Library on Google APIs
JSON Datetime Between Python and JavaScript
A Component Is Changing an Uncontrolled Input of Type Text to Be Controlled Error in Reactjs
Passing Parameters to JavaScript Files
How to Beautify JSON Programmatically
HTML - How to Show Tooltip Only When Ellipsis Is Activated
How to Append Timestamp to the JavaScript File in <Script> Tag Url to Avoid Caching
How to Do Page Numbering in Header/Footer HTMLs with Wkhtmltopdf