Home >Web Front-end >JS Tutorial >How to Efficiently Extract Specific Properties from an 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})
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]}))); }
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)}))) ); }
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!