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

How to Selectively Extract Object Properties in ES6?

Linda Hamilton
Release: 2024-12-17 11:12:26
Original
459 people have browsed it

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

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

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

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!

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