Home > Web Front-end > JS Tutorial > How to Extract Specific Properties from a JavaScript Object?

How to Extract Specific Properties from a JavaScript Object?

Mary-Kate Olsen
Release: 2024-12-11 20:33:13
Original
699 people have browsed it

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'}
};
Copy after login

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);
Copy after login

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' }
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template