How to Pluck Properties from JavaScript Objects?

Estimated read time 1 min read

To pluck specific properties from a JavaScript object, you can use destructuring assignment to create a new object containing only the desired properties. Here’s an example:

let person = {
  name: "John",
  age: 30,
  occupation: "Developer",
  location: "San Francisco"
};

let { name, age } = person;

console.log(name); // outputs "John"
console.log(age); // outputs 30

In this example, we define a person object with four properties: name, age, occupation, and location. We then use destructuring assignment to create a new object containing only the name and age properties. The resulting name and age variables contain the corresponding values from the person object.

You can also use object destructuring directly in a function’s parameter list to pluck properties from an object passed as an argument. For example:

function printNameAndAge({ name, age }) {
  console.log(`Name: ${name}, Age: ${age}`);
}

printNameAndAge(person); // outputs "Name: John, Age: 30"

In this example, the printNameAndAge() function takes an object as a parameter and uses destructuring assignment to pluck the name and age properties from the object. The function then logs a formatted string containing the name and age properties.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply