Home >Web Front-end >JS Tutorial >How to Selectively Extract Object Properties in ES6?

How to Selectively Extract Object Properties in ES6?

Linda Hamilton
Linda HamiltonOriginal
2024-12-17 11:12:26529browse

How to Selectively Extract Object Properties in ES6?

One-liner to Take Specific Properties from an Object in ES6

Q: How can you extract only certain attributes from an object in a concise manner using ES6?

A: Here are a few approaches:

Most Compact Approach:

Using parameter destructuring to avoid using a parameter variable:

({id, title}) => ({id, title})

Generalized Approach:

This method uses Object.assign and computed properties to achieve a more general solution:

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

Preserving Property Attributes:

If you need to preserve the properties' attributes, such as configurability, getters, and setters, while excluding non-enumerable properties, use this approach:

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

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