How to Select Properties from an Object Using ES6
In ES6, JavaScript provides several methods for selecting specific properties from an object in a concise manner.
Using Destructuring
One approach is to use destructuring, which allows you to assign specific properties to variables in a single line:
({ id, title }) => ({ id, title });
Using Parameter Destructuring
An even slimmer solution is to use parameter destructuring, eliminating the need for an explicit v parameter:
({id, title}) => ({id, title});
Using Object.assign()
For more flexibility, you can use Object.assign() to create a new object with the selected properties:
function pick(o, ...props) { return Object.assign({}, ...props.map(prop => ({[prop]: o[prop]}))); }
Preserving Property Attributes
If you need to preserve the original property attributes (configurable, getters, setters), you can use:
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(prop)}))) ); }
The above is the detailed content of How to Efficiently Select Properties from a JavaScript Object Using ES6?. For more information, please follow other related articles on the PHP Chinese website!