What are computed names ("dynamic" structuring) in Javascript?

Asked

Viewed 303 times

16

Reading the documentation of dismantling in Javascript, I found the section below:

Computed object property and destructuring names

Computed property names, as in literal objects, can be used with breakdown.

let key = "z";
let { [key]: foo } = { z: "bar" };

console.log(foo); // "bar"

But I didn’t understand what a computed name would be. I also didn’t understand the quoted code and I wonder if it has any use in the "real world".

2 answers

18


Basically, it is a facilitator to access properties dynamically within a breakdown.

What is a breakdown?

First, it is worth mentioning what is the structuring of objects in Javascript. For this, consider the example below:

const myObject = {
  name: 'John Doe',
  age: 50
};

// Estamos desestruturando a propriedade `name` do objeto `myObject`.
const { name, age } = myObject;

// Anteriormente, a forma mais simples de se alcançar o mesmo efeito:
const name = myObject.name;
const age = myObject.age;

Note then that structuring is a simple way to extract some values from within an object, creating variables in the current scope according to the names of the respective properties.

And if you want to unstructure a property of an object by assigning another name to the variable that will be created, you can use this syntax:

const myObject = {
  name: 'John Doe'
};

// No exemplo abaixo, `name` é a propriedade que queremos
// desestruturar do objeto. E `prop` é o nome da variável
// que será criada a partir da desestruturação.
// Se omitíssemos `: prop` da construção abaixo, uma variável
// `name` criar-se-ia no escopo atual. Então...

// Nome da propriedade que estaremos "acessando" (desestruturando) do objeto.
//      ↓↓↓↓
const { name: prop } = myObject;
//            ↑↑↑↑
// Nome da variável que será criada.

console.log(prop); // John Doe


Structuring "in a dynamic way"

Destructuring via computed properties allows you to perform destructuring even if you don’t "know statically" the key you want to access. In other words, rather than being "unstructured static", there is a "breakdown dynamics".

The simplest way to access a property from an expression ("dynamics") is to use the bracket notation to access the object property. See:

const myDynamicKey = 'name';

const myObject = {
  name: 'John Doe'
};

// O que faremos abaixo é a mesma coisa que:
//
//   ```
//   myObject.name;
//   ```
//
// Só que estamos utilizando uma outra variável,
// que está representando a chave que queremos acessar.
//
// Isso é útil para acessar propriedades de forma dinâmica.
// A propriedade a ser lida virá da avaliação de `myDynamicKey`:
//                   ↓↓↓↓↓↓↓↓↓↓↓↓↓↓
const prop = myObject[myDynamicKey];

console.log(prop); // John Doe

Now, if we want to do this using de-structuring:

const myDynamicKey = 'name';

const myObject = {
  name: 'John Doe'
};

// Estamos declarando uma variável `prop` que virá
// da desestruturação de uma propriedade computada.
//
// A propriedade que iremos desestruturar do objeto
// virá do valor de `myDynamicKey`. No caso, como
// `myDynamicKey` é "name", então iremos acessar, de
// forma dinâmica, a propriedade `name` de `myObject`.
const { [myDynamicKey]: prop } = myObject;

console.log(prop); // John Doe

So unlocking our disruption above:

// Computação dinâmica que estamos fazendo. A propriedade
// correspondente ao valor de `myDynamicKey` será desestruturada
// de forma dinâmica.
//      ↓↓↓↓↓↓↓↓↓↓↓↓↓↓
const { [myDynamicKey]: prop } = myObject;
//                      ↑↑↑↑
// Variável que criamos para o resultado dessa computação dinâmica.
// Como estamos utilizando uma computação dinâmica nessa desestruturação,
// somos forçados a criar uma variável explicitamente na nossa desestruturação.

I confess that I prefer to use the old notation in this type of situation, since it is more explicit what we are actually doing. This type of syntax can be a bit "obscure" for new language learners.

8

As you can see, an object property in JS is actually an index key of a array associative, then every code symbol (which can be naturally confused with an object variable) used to access a property is actually a string with the name of this symbol. So you can access:

obj.propriedade

or

obj["propriedade"]

or

var nome = "propriedade";
obj[nome];

or

obj[prompt()]; //desde que digite propriedade quando pedir o dado

All the same, it works.

So when you access through an expression, be a variable, a prompt() crazy like I used, or in a way that you calculate the text of string used, you are using a computed property name.

You can see more details on JS native objects are associative arrays?. See also.

Example:

var pessoa = {
    nome: "João",
    animais: {
        cachorro: "Rex",
        gato: "Pipoca",
    }
}

console.log(pessoa["animais"]["gato"]);

I put in the Github for future reference.

People are dazzled by this when they discover and begin to do things that are daunting and unnecessary, in general having an easier, more performative, more robust, or at least more correct way of doing the same. And we can still talk about more secure when using on the server, at least in some cases.

As seen you can access a property according to a user input. But imagine how dangerous it is to give this chance without a very strong validation. It is very easy for the user to enter with a wrong data and the code to break because of this.

A consequence of this can be seen in Why the behavior of the undefined variable is different from the undefined property?.

Some people use it to save code typing or to show that it is "very smart" and makes code unreadable and difficult to maintain. It’s a way of generalizing code, but it almost always doesn’t look good.

So if you really need access to a property to be done in some way to be determined at the time of execution this mechanism may be useful.

I’ve abused it so much in other languages that today I’m sure it’s not really necessary. So as object properties I see no advantage in using it except for laziness, distraction or if I’m making a framework that needs a generalization of how to proceed, for example an object to be created based on some external information, such as a JSON for example. This is a case where you do not know how the object is composed before you receive it. There you can create an object access mechanism without knowing its properties. You can’t do much, but you can access all the properties in a generic way. If it is only to make a display of all content of the object for example, you can make a code using a computed name.

You can use creativity to do some cool things, but almost always will be abuse.

These computed names are much more useful when using a array normal associative and not one that has become an object like in Javascript. There a dictionary application for example has the keyword and the dictionary description as value, it makes a lot of sense. A example.

Browser other questions tagged

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