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!