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

How to Efficiently Extract Specific Properties from an Object in ES6?

Linda Hamilton
Release: 2024-12-21 18:29:10
Original
220 people have browsed it

How to Efficiently Extract Specific Properties from an Object in ES6?

One-liner to Take Some Properties from Object in ES6

Problem:

The goal is to create a concise function in ES6 that extracts specific properties from an object. A solution involving destructuring and simplified object literals is presented, but concerns arise regarding the repetition of field lists.

Answer:

To achieve a slimmer solution, consider using parameter destructuring to eliminate the need for an explicit parameter:

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

While parameter destructuring is convenient, it still requires repeating the property list. For a more general solution, employ the following:

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

This solution utilizes Object.assign to merge objects while preserving specified properties (props).

Additional Considerations for Property Attributes:

If it's crucial to retain the attributes of the original properties (such as configurability and getters/setters), and exclude non-enumerable properties, consider the following:

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 Efficiently Extract Specific Properties from an Object in ES6?. For more information, please follow other related articles on the PHP Chinese website!

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