# TypeScript/JavaScript Extract target keys from an object

A variable name can be too long to be referred to many times. If it is an object, the name to access one of the child variables gets long. This is an example. It’s a long name.

const personInformationWithAddress = {
name: "Yuto",
age: 34,
postalCode: 12345,
city: "city",
street: 99,
},
};
// {
//     name: 'Yuto',
//     age: 34,
//     address: { postalCode: 12345, city: 'city', street: 99 }
// }

In this case, we might want to declare a new variable and assign the value to it. Curly braces and brackets can be used for this purpose with one line. Let’s check how can we make it readable.

## Extract variables from an object

If we want to access the value in the object, it gets too long.

console.log(name: ${personInformationWithAddress.name}); // name: Yuto console.log(age:${personInformationWithAddress.age});            // age: 34
console.log(city: ${personInformationWithAddress.address.city}); // city: city Some developers think it’s ok, some think it’s not readable… The easiest solution for this is to declare new variables. The result is still the same but the 3 lines in console.log get more readable. const person = personInformationWithAddress; console.log(name:${person.name});          // name: Yuto
console.log(age: ${person.age}); // age: 34 console.log(city:${person.address.city});  // city: city

Some think that declaring a temp variable without adding extra information doesn’t make sense. As far as I remember, a similar thing is written in a book called REFACTORING by Martin Fowler. It depends on the situation which way to apply, but I use the original variable more often than declaring the temp variable because the too-long name doesn’t exist very much.

Sometimes, we don’t need all variables defined in the object. The following ways might be better in this case.

### Assign the value to a new variable

If the variable is an object, we can extract the variables from it in this way.

const { name, age } = personInformationWithAddress;
console.log(name: ${name}); // name: Yuto console.log(age:${age});     // age: 34

It looks simpler than the previous ones. We can extract only desired variables. Note that the variable names used in the curly braces must be declared in the object.

### Rename the variables

The variable names are sometimes not proper names. We want to rename it in this case. If we want to rename it we can write the new name on the right-side separated by a semicolon.

const { name: newName } = personInformationWithAddress;
console.log(newName: ${newName}); // newName: Yuto  The original variable name can’t be used in this case. ### Extract variable from an object in an object Extract an object from an object? Of course, it’s possible. const { postalCode, city } = personInformationWithAddress.address; console.log(address:${postalCode}, ${city}); // address: 12345, city Yes, but I want to extract top-level variables as well in the same code!! How can I implement it in this case? const { name, address: { postalCode, city, } } = personInformationWithAddress; console.log(name:${name});   //name: Yuto
console.log(address: ${postalCode},${city}); // address: 12345, city

We can access the deep level variables without dot chain in this way.
Do you also want to know how to rename the deep level variable name? Here it is.

const {
name,
postalCode: code,
city: cityName,
}
console.log(name: ${name}); //name: Yuto console.log(address:${code}, ${cityName}); // address: 12345, city ## Extract variables from an array Let’s learn how to do the same thing for array. Array is often used and the number of elements is fixed in some cases but it doesn’t have the variable name. If a new developer looks at the following code, he has to check the other code where the values are assigned. const personInfoArray = ["Yuto", 34, "city"]; func1(personInfoArray[0], personInfoArray[1], personInfoArray[2]); We can ASSUME those variables’ meanings but they are not clear. The code gets longer but the following code is more readable because each variable is clear. const personInfoArray = ["Yuto", 34, "city"]; const name = personInfoArray[0]; const age = personInfoArray[1]; const city = personInfoArray[2]; func1(name, age, city); Let’s check the different ways. ### Assign the value to a new variable The same technique as the one for objects can be used for the array as well. const personInfoArray = ["Yuto", 34, "city"]; const [name, age, city] = personInfoArray; console.log(name:${name});   // name: Yuto
console.log(age: ${age}); // age: 34 console.log(city:${city});   // city: city

Note that the order of the declaration in the array on the left side must match the order of the target array on the right side.

### Object array

Of course, we can use this technique if the array is an object array.

const personInfoArray = [
{ name: "Yuto", age: 34 },
{ name: "Peter", age: 22 },
{ name: "Jack", age: 59 },
];

const [yuto, peter, jack] = personInfoArray;
console.log("Yuto => ", yuto.name, yuto.age);       // Yuto =>  Yuto 34
console.log("Peter => ", peter.name, peter.age);    // Peter =>  Peter 22
console.log("Jack => ", jack.name, jack.age);       // Jack =>  Jack 59

We can access the objects via the new variables but the following code is better if we just want to use it like this.

personInfoArray.forEach((person) => console.log(\${person.name} =>, person.name, person.age));
// Yuto => Yuto 34
// Peter => Peter 22
// Jack => Jack 59

### Extract first values and the rest by Spread operator

There might be some cases that we want to handle the first argument differently. Then, extract the first arguments and do the different processes for the rest of the array.

const [yuto, ...others] = personInfoArray;
console.log(yuto);      // { name: 'Yuto', age: 34 }
console.log(others);    // [ { name: 'Peter', age: 22 }, { name: 'Jack', age: 59 } ]

The spread operator must be at the end. Otherwise, the compiler shows an error.

Check this post as well if you are not familiar with the three dots called spread operator.

### Get discontinuous index values

I guess this is a rare case but let’s show an example.

 'hoge' is declared but its value is never read.
const [courseNumber, _1, _2, _3, numberOfPeople, hoge] = [1, 2, 3, 4, 5, 6, 7];
console.log(courseNumber);      // 1
console.log(numberOfPeople);    // 5

Underscore is used to tell the compiler that the variables are not used. It shows a warning without the underscore.
It’s better to consider the data structure if we need to write such a code.