Home >Web Front-end >JS Tutorial >How to Extract Specific Properties from a JavaScript Object?
Object Subsetting in JavaScript: Extracting Specific Properties
In various scenarios, we encounter objects with numerous properties, and extracting a specific subset can become essential. This question explores how to achieve this objective in JavaScript.
Consider the following object elmo:
elmo = { color: 'red', annoying: true, height: 'unknown', meta: { one: '1', two: '2'} };
The goal is to create a new object, subset, that includes only a portion of these properties, such as color and height.
Solution 1: Using Destructuring and Property Shorthand
One effective solution utilizes object destructuring and property shorthand. This approach leverages the curly brace syntax (${}), allowing for dynamic creation and assignment of new objects:
const subset = ({ color, height }) => ({ color, height })(elmo);
In this code, a new arrow function is defined that takes an object as its parameter. Within the curly braces, the desired properties are specified using property shorthand, which automatically assigns the extracted values to these properties in the new object. When the arrow function is invoked with the elmo object as its argument, the resulting object subset contains only the color and height properties.
Example Output:
{ color: 'red', height: 'unknown' }
The above is the detailed content of How to Extract Specific Properties from a JavaScript Object?. For more information, please follow other related articles on the PHP Chinese website!