Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring and rename property

const a = {
 b: {
  c: 'Hi!'
 }
};

const { b: { c } } = a;

Is it possible rename b in this case? I want get c and also rename b.

like image 425
leusrox Avatar asked Jul 16 '19 20:07

leusrox


People also ask

What is Destructure property?

Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array​ at a time.

What does Destructuring mean?

To destroy the structure of something. To dismantle.

What does it mean to Destructure an object?

JavaScript Object Destructuring is the syntax for extracting values from an object property and assigning them to a variable. The destructuring is also possible for JavaScript Arrays. By default, the object key name becomes the variable that holds the respective value.

Why would you Destructure an array?

Destructuring can make working with an array return value more concise. In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.


2 Answers

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);
like image 88
Nina Scholz Avatar answered Oct 19 '22 09:10

Nina Scholz


You can destructure the same property multiple times, onto different targets:

const { b: {c}, b: d } = a;

This assigns a.b.c to c and a.b to d.

like image 33
Bergi Avatar answered Oct 19 '22 07:10

Bergi