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
Susan SarandonOriginal
2024-12-20 05:44:10834browse

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'}
};

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

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

The resulting subset object will contain only these two properties:

{ color: 'red', height: 'unknown' }

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

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

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'])

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!

Statement:
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