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

How to Extract Specific Object Properties in JavaScript?

Mary-Kate Olsen
Release: 2024-12-20 09:17:10
Original
607 people have browsed it

How to Extract Specific Object Properties in JavaScript?

How to Extract and Copy Object Properties in JavaScript

Suppose you have an object named elmo with various properties. You wish to create a new object containing only a specified subset of these properties.

Object Destructuring and Property Shorthand Method:

To achieve this using object destructuring and property shorthand, follow these steps:

  1. Use the const keyword to declare a new object.
  2. In parentheses, enclose the object you want to extract properties from.
  3. Use curly braces to enclose the properties you want to extract, separated by commas.
  4. Use the arrow function syntax (({ ... }) => ({ ... })) to define the new object with the selected properties.

Example:

const elmo = { 
  color: 'red',
  annoying: true,
  height: 'unknown',
  meta: { one: '1', two: '2'}
};

const subset = (({ color, height }) => ({ color, height }))(elmo);

console.log(subset); // { color: 'red', height: 'unknown' }
Copy after login

This method allows you to create a new object named subset containing only the color and height properties from the original elmo object.

The above is the detailed content of How to Extract Specific Object Properties in JavaScript?. 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