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

How to Efficiently Extract a Subset of Properties from a JavaScript Object?

Susan Sarandon
Release: 2024-12-20 05:44:10
Original
835 people have browsed it

How to Efficiently Extract a Subset of Properties from a JavaScript Object?

How to Extract a Subset of Properties from a JavaScript Object

Often when working with JavaScript objects, it's necessary to create a new object that only includes a specific set of properties from the original object. For example, consider the following object:

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

To create a new object with only the color and height properties, you can use object destructuring:

const subset = { ...elmo, color: 'red', height: 'unknown' }
Copy after login

The resulting subset object will contain only these two properties:

{ color: 'red', height: 'unknown' }
Copy after login

Another alternative is to use the Object.assign() method:

const subset = Object.assign({}, elmo, { color: 'red', height: 'unknown' })
Copy after login

This method creates a new object by merging the properties of the existing object (in this case, elmo) with the newly assigned properties.

Finally, you can also use the _.pick() method from the popular lodash library:

const subset = _.pick(elmo, ['color', 'height'])
Copy after login

No matter which method you choose, object destructuring offers a concise and flexible way to extract a subset of properties from a JavaScript object.

The above is the detailed content of How to Efficiently Extract a Subset of 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