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

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

DDD
Release: 2024-12-15 09:48:12
Original
187 people have browsed it

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

One-liner to Extract Properties from an Object in ES6

Problem:

How can you write a function that selects specific properties from an object in the most concise manner in ES6?

Initial Solution:

The following approach uses destructuring and a simplified object literal to achieve this:

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

Improved Solution:

A more streamlined solution, which also eliminates the repetition of property names, can be achieved through parameter destructuring:

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

This solution provides a more concise alternative while retaining the desired functionality.

Alternative Approaches:

  • Object.assign: This approach can be used to preserve the attributes of the original properties while also filtering out 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

The above is the detailed content of How to Concisely 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template