Es6/Es2015 Object Destructuring and Changing Target Variable

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



Leave a reply



Submit