js function pick properties from object
Understanding JavaScript Functions that Pick Properties from Objects
As a JavaScript developer, you may have come across objects and their properties. Sometimes, you may only need to work with specific properties of an object rather than the entire object. In such cases, you can use a JavaScript function that picks properties from objects.
Let's say you have an object with several properties:
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
gender: 'male',
occupation: 'web developer'
};
Method 1: Using Destructuring Assignment
You can use destructuring assignment to pick only the properties you need from the object:
const { firstName, lastName } = person;
console.log(firstName); // 'John'
console.log(lastName); // 'Doe'
In this example, we are only picking the firstName
and lastName
properties from the person
object. This creates two new variables with the same names as the properties and assigns their values to them.
Method 2: Using Object Methods
You can also use object methods like Object.keys()
and Object.values()
to pick properties from an object:
const keys = Object.keys(person); // returns an array of property names
const values = Object.values(person); // returns an array of property values
console.log(keys); // ['firstName', 'lastName', 'age', 'gender', 'occupation']
console.log(values); // ['John', 'Doe', 30, 'male', 'web developer']
These methods return an array of either property names or property values, which you can then manipulate as needed.
Method 3: Using Spread Syntax
You can also use spread syntax to pick properties from an object:
const { firstName, ...rest } = person; // picks firstName and the rest of the properties
console.log(firstName); // 'John'
console.log(rest); // { lastName: 'Doe', age: 30, gender: 'male', occupation: 'web developer' }
In this example, we are using spread syntax to pick the firstName
property and the rest of the properties are stored in the rest
variable.
Conclusion
There are several ways to pick properties from objects in JavaScript. Depending on your requirements, you can choose the method that best suits your needs. From destructuring assignment, to object methods, to spread syntax, each approach has its own advantages and disadvantages. Choose wisely!