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