How does attribution work via disruption?

Asked

Viewed 409 times

2

I don’t understand how the assignment works via unstructuring. It’s something specific to JSON?

An example of the body of a request to Node.js:

{
  "title": "Caso 1",
  "description": "Detalhes do caso",
  "value": 1100
}
async create(request, response) {
  const { title, description, value } = request.body;
}

For each value a variable is created.

1 answer

4


Breakdown assignment is a feature introduced in Ecmascript 2015 (ES6). It is basically a syntactic sugar to obtain object values or arrays.

In your example, you are disrupting the properties title, description and value of the object request.body:

const body = {
  title: 'Sou o "Title"',
  description: 'Sou a "Description"',
  value: 'Sou o "Value"',
  foo: 'Foo'
};

const { title, description, value } = body;

console.log(title, description, value);

Note that the object may have more properties. We will only get, however, those that we disrupt.

By way of comparison, to do the same thing in versions prior to ES6, you would have to do:

const body = {
  title: 'Sou o "Title"',
  description: 'Sou a "Description"',
  value: 'Sou o "Value"',
  foo: 'Foo'
};

const title = body.title;
const description = body.description;
const value = body.value;

console.log(title, description, value);

Note that there is a significant line saving, which grows as we disrupt more properties. The syntax goes much further than that, see documentation to learn more about the various use-cases.

There is also disruption of arrays. See a simple example:

const arr = [1, 2, 3, 4, 5];

const [one, two] = arr;

console.log(one, two);


Finally, it is important to say that this is not something "specific to JSON". JSON is a data transfer format compatible with Javascript objects. Thus, you can unstructure any object or array using these syntaxes. See the example below, which illustrates the structuring of the property name of a function:

function doStuff() {}

const { name } = doStuff;

console.log(`O nome é: "${name}".`);

Anyway, it is a very useful addition that facilitates basant.


This answer explains how computed names work, a more complex resource of assignment via disruption.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.