How to Extract Properties from an Object in JavaScript?

Estimated read time 2 min read

You can extract properties from an object in JavaScript using object destructuring. Object destructuring allows you to extract the properties of an object and assign them to variables with the same name.

Here’s an example:

let obj = { name: "John Doe", age: 30, city: "New York" };
let { name, age } = obj;
console.log(name);
// Output: "John Doe"
console.log(age);
// Output: 30

In the example, the obj object has three properties: name, age, and city. The object destructuring syntax { name, age } is used to extract the name and age properties from the object and assign them to variables with the same name. The extracted properties can then be accessed using the variables, as shown in the console.log statements.

You can also use object destructuring to extract properties from an object and assign them to variables with different names:

let obj = { name: "John Doe", age: 30, city: "New York" };
let { name: fullName, age: ageInYears } = obj;
console.log(fullName);
// Output: "John Doe"
console.log(ageInYears);
// Output: 30

In this example, the name property is extracted from the obj object and assigned to the fullName variable, and the age property is extracted and assigned to the ageInYears variable. The extracted properties can then be accessed using the new variable names.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply