JavaScriptで配列とオブジェクトの破棄を使用する方法

破壊の割り当ては、ES6に付属していたクールな機能です。デストラクチャリングは、配列の値またはオブジェクトのプロパティを個別の変数に解凍できるようにするJavaScript式です。つまり、配列とオブジェクトからデータを抽出し、それらを変数に割り当てることができます。

なぜこれが必要なのですか?

配列からデータを抽出したいとします。以前は、これはどのように行われますか?

let introduction = ["Hello", "I" , "am", "Sarah"]; let greeting = introduction[0]; let name = introduction[3]; console.log(greeting);//"Hello" console.log(name);//"Sarah" 

配列からデータを抽出する場合、同じことを何度も繰り返す必要があることがわかります。

ES6の非構造化割り当てにより、このデータの抽出が容易になります。これはどうですか?最初に、配列を使用した破壊的割り当てについて説明します。次に、オブジェクトの破壊に移ります。

始めましょう。

基本的なアレイの破壊

配列からデータを抽出する場合は、破棄割り当てを使用すると非常に簡単です。

配列の最初の例を参照してみましょう。その繰り返しのプロセスを経る代わりに、これを行います:

let introduction = ["Hello", "I" , "am", "Sarah"]; let [greeting, pronoun] = introduction; console.log(greeting);//"Hello" console.log(pronoun);//"I" 

これも同じ結果で実行できます。

let [greeting, pronoun] = ["Hello", "I" , "am", "Sarah"]; console.log(greeting);//"Hello" console.log(pronoun);//"I"

代入前の変数の宣言

変数は、次のように割り当てる前に宣言できます。

 let greeting, pronoun; [greeting, pronoun] = ["Hello", "I" , "am", "Sarah"]; console.log(greeting);//"Hello" console.log(pronoun);//"I" 

変数が左から右に設定されていることに注意してください。したがって、最初の変数は配列の最初の項目を取得し、2番目の変数は配列の2番目の変数を取得します。

配列内のアイテムをスキップする

最初と2番目の項目ではなく、配列の最初と最後の項目を取得し、2つの変数のみを割り当てたい場合はどうなりますか?これも実行できます。以下の例を見てください。

let [greeting,,,name] = ["Hello", "I" , "am", "Sarah"]; console.log(greeting);//"Hello" console.log(name);//"Sarah" 

今何があったの?

変数割り当ての左側にある配列を見てください。カンマが1つだけではなく、3つあることに注意してください。配列の値をスキップするには、コンマ区切り記号を使用します。したがって、配列内の項目をスキップする場合は、コンマを使用してください。

別のことをしましょう。リストの最初と3番目の項目をスキップしましょう。これをどのように行いますか?

let [,pronoun,,name] = ["Hello", "I" , "am", "Sarah"]; console.log(pronoun);//"I" console.log(name);//"Sarah" 

したがって、コンマ区切りは魔法を実行します。したがって、すべての項目をスキップしたい場合は、次のようにします。

let [,,,,] = ["Hello", "I" , "am", "Sarah"]; 

配列の残りの部分を割り当てる

配列の一部を変数に割り当て、配列内の残りの項目を特定の変数に割り当てたい場合はどうなりますか?その場合、これを行います。

let [greeting,...intro] = ["Hello", "I" , "am", "Sarah"]; console.log(greeting);//"Hello" console.log(intro);//["I", "am", "Sarah"] 

このパターンを使用すると、配列の残りの部分を解凍して変数に割り当てることができます。

関数を使用した代入の破棄

関数から返された配列からデータを抽出することもできます。以下の例のような配列を返す関数があるとしましょう。

function getArray() { return ["Hello", "I" , "am", "Sarah"]; } let [greeting,pronoun] = getArray(); console.log(greeting);//"Hello" console.log(pronoun);//"I" 

同じ結果が得られます。

デフォルト値の使用

配列から抽出された値が次の場合に備えて、デフォルト値を変数に割り当てることができますundefined

let [greeting = "hi",name = "Sarah"] = ["hello"]; console.log(greeting);//"Hello" console.log(name);//"Sarah" 

したがってname、配列で定義されていないため、「Sarah」にフォールバックします。

破棄割り当てを使用した値の交換

もう一つ。破壊割り当てを使用して、変数の値を交換できます。

let a = 3; let b = 6; [a,b] = [b,a]; console.log(a);//6 console.log(b);//3 

次に、オブジェクトの破棄に移りましょう。

オブジェクトの破壊

まず、オブジェクトの破棄が必要な理由を見てみましょう。

オブジェクトからデータを抽出し、新しい変数に割り当てたいとします。ES6より前は、これはどのように行われますか?

let person = {name: "Sarah", country: "Nigeria", job: "Developer"}; let name = person.name; let country = person.country; let job = person.job; console.log(name);//"Sarah" console.log(country);//"Nigeria" console.log(job);//Developer" 

See how tedious it is to extract all the data. We have to repeatedly do the same thing. ES6 destructuring really saves the day. Let's jump right into it.

Basic Object Destructuring

Let's repeat the above example with ES6. Instead of assigning values one by one, we can use the object on the left to extract the data:

 let person = {name: "Sarah", country: "Nigeria", job: "Developer"}; let {name, country, job} = person; console.log(name);//"Sarah" console.log(country);//"Nigeria" console.log(job);//Developer" 

You'll get the same results. It is also valid to assign variables to an object that haven't been declared:

let {name, country, job} = {name: "Sarah", country: "Nigeria", job: "Developer"}; console.log(name);//"Sarah" console.log(country);//"Nigeria" console.log(job);//Developer" 

Variables declared before being assigned

Variables in objects can be declared before being assigned with destructuring. Let's try that:

let person = {name: "Sarah", country: "Nigeria", job: "Developer"}; let name, country, job; {name, country, job} = person; console.log(name);// Error : "Unexpected tokenSarah", country: "Nigeria", job: "Developer"}; let name, country, job; ({name, country, job} = person); console.log(name);//"Sarah" console.log(job);//"Developer" 

It is also important to note that when using this syntax, the () should be preceded by a semicolon. Otherwise it might be used to execute a function from the previous line.

Note that the variables in the object on the left hand side should have the same name as a property key in the object person. If the names are different, we'll get undefined:

let person = {name: "Sarah", country: "Nigeria", job: "Developer"}; let {name, friends, job} = person; console.log(name);//"Sarah" console.log(friends);//undefined 

But if we want to use a new variable name, well, we can.

Using a new Variable Name

If we want to assign values of an object to a new variable instead of using the name of the property, we can do this:

let person = {name: "Sarah", country: "Nigeria", job: "Developer"}; let {name: foo, job: bar} = person; console.log(foo);//"Sarah" console.log(bar);//"Developer" 

So the values extracted are passed to the new variables foo and bar.

Using Default Values

Default values can also be used in object destructuring, just in case a variable is undefined in an object it wants to extract data from:

let person = {name: "Sarah", country: "Nigeria", job: "Developer"}; let {name = "myName", friend = "Annie"} = person; console.log(name);//"Sarah" console.log(friend);//"Annie" 

So if the value is not undefined, the variable stores the value extracted from the object as in the case of name. Otherwise, it used the default value as it did for friend.

We can also set default values when we assign values to a new variable:

let person = {name: "Sarah", country: "Nigeria", job: "Developer"}; let {name:foo = "myName", friend: bar = "Annie"} = person; console.log(foo);//"Sarah" console.log(bar);//"Annie" 

So  name was extracted from person and assigned to a different variable. friend, on the other hand, was undefined in person, so the new variable bar  was assigned the default value.

Computed Property Name

Computed property name is another object literal feature that also works for destructuring. You can specify the name of a property via an expression if you put it in square brackets:

let prop = "name"; let {[prop] : foo} = {name: "Sarah", country: "Nigeria", job: "Developer"}; console.log(foo);//"Sarah" 

Combining Arrays with Objects

Arrays can also be used with objects in object destructuring:

let person = {name: "Sarah", country: "Nigeria", friends: ["Annie", "Becky"]}; let {name:foo, friends: bar} = person; console.log(foo);//"Sarah" console.log(bar);//["Annie", "Becky"] 

Nesting in Object Destructuring

Objects can also be nested when destructuring:

let person = { name: "Sarah", place: { country: "Nigeria", city: "Lagos" }, friends : ["Annie", "Becky"] }; let {name:foo, place: { country : bar, city : x} } = person; console.log(foo);//"Sarah" console.log(bar);//"Nigeria" 

Rest in Object Destructuring

The rest syntax can also be used to pick up property keys that are not already picked up by the destructuring pattern. Those keys and their values are copied into a new object:

let person = {name: "Sarah", country: "Nigeria", job: "Developer" friends: ["Annie", "Becky"]}; let {name, friends, ...others} = person; console.log(name);//"Sarah" console.log(friends);//["Annie", "Becky"] console.log(others);// {country: "Nigeria", job: "Developer"} 

Here, the remaining properties whose keys where not part of the variable names listed were assigned to the variable others. The rest syntax here is ...others. others can be renamed to whatever variable you want.

One last thing – let's see how Object Destructing can be used in functions.

Object Destructuring and Functions

Object Destructuring can be used to assign parameters to functions:

function person({name: x, job: y} = {}) { console.log(x); } person({name: "Michelle"});//"Michelle" person();//undefined person(friend);//Error : friend is not defined 

Notice the {} on the right hand side of the parameters object. It makes it possible for us to call the function without passing any arguments. That is why we got undefined. If we remove it, we'll get an error message.

We can also assign default values to the parameters:

function person({name: x = "Sarah", job: y = "Developer"} = {}) { console.log(x); } person({name});//"Sarah" 

We can do a whole lot of things with Array and Object Destructuring as we have seen in the examples above.

Thank you for reading. :)