Home > Web Front-end > JS Tutorial > How Can I Efficiently Extract Specific Properties from an Object in ES6?

How Can I Efficiently Extract Specific Properties from an Object in ES6?

Barbara Streisand
Release: 2024-12-24 17:32:14
Original
186 people have browsed it

How Can I Efficiently Extract Specific Properties from an Object in ES6?

One-liner to Take Properties from Object in ES6

Many developers have sought a concise method for extracting specific properties from objects in ES6. One common solution employs destructuring and simplified object literals, though repeating the list of fields in the code can be cumbersome.

Improved Solution

A more streamlined approach involves "parameter destructuring," which eliminates the need for an explicit parameter:

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

Generalized Solution

For greater flexibility, consider the "pick" function, which accepts an object and an arbitrary number of properties as arguments:

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

Preserving Property Attributes

To preserve property attributes like configurability and getters/setters while excluding non-enumerable properties:

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

These solutions provide a concise and versatile means of extracting specific properties from objects in ES6, catering to various use cases.

The above is the detailed content of How Can I Efficiently Extract Specific Properties from an Object in 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