Home > Web Front-end > JS Tutorial > How to Efficiently Select Properties from a JavaScript Object Using ES6?

How to Efficiently Select Properties from a JavaScript Object Using ES6?

Patricia Arquette
Release: 2024-12-18 01:46:09
Original
150 people have browsed it

How to Efficiently Select Properties from a JavaScript Object Using ES6?

How to Select Properties from an Object Using ES6

In ES6, JavaScript provides several methods for selecting specific properties from an object in a concise manner.

Using Destructuring

One approach is to use destructuring, which allows you to assign specific properties to variables in a single line:

({ id, title }) => ({ id, title });
Copy after login

Using Parameter Destructuring

An even slimmer solution is to use parameter destructuring, eliminating the need for an explicit v parameter:

({id, title}) => ({id, title});
Copy after login

Using Object.assign()

For more flexibility, you can use Object.assign() to create a new object with the selected properties:

function pick(o, ...props) {
    return Object.assign({}, ...props.map(prop => ({[prop]: o[prop]})));
}
Copy after login

Preserving Property Attributes

If you need to preserve the original property attributes (configurable, getters, setters), you can use:

function pick(o, ...props) {
    var has = p => o.propertyIsEnumerable(p),
        get = p => Object.getOwnPropertyDescriptor(o, p);

    return Object.defineProperties({},
        Object.assign({}, ...props
            .filter(prop => has(prop))
            .map(prop => ({prop: get(prop)})))
    );
}
Copy after login

The above is the detailed content of How to Efficiently Select Properties from a JavaScript Object Using ES6?. 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