Saturday, May 11, 2024
191
rated 0 times [  193] [ 2]  / answers: 1 / hits: 75145  / 10 Years ago, thu, august 28, 2014, 12:00:00

How one can write a function, which takes only few attributes in most-compact way in ES6?



I've came up with solution using destructuring + simplified object literal, but I don't like that list of fields is repeated in the code.



Is there an even slimmer solution?



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

More From » ecmascript-6

 Answers
53

Here's something slimmer, although it doesn't avoid repeating the list of fields. It uses parameter destructuring to avoid the need for the v parameter.



({id, title}) => ({id, title})


(See a runnable example in this other answer).



@EthanBrown's solution is more general. Here is a more idiomatic version of it which uses Object.assign, and computed properties (the [p] part):



function pick(o, ...props) {
return Object.assign({}, ...props.map(prop => ({[prop]: o[prop]})));
}


If we want to preserve the properties' attributes, such as configurable and getters and setters, while also omitting non-enumerable properties, then:



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

[#69623] Tuesday, August 26, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gerardob

Total Points: 571
Total Questions: 115
Total Answers: 96

Location: Cyprus
Member since Mon, Oct 24, 2022
2 Years ago
gerardob questions
Fri, Jan 22, 21, 00:00, 3 Years ago
Thu, Jan 14, 21, 00:00, 3 Years ago
Tue, Jan 28, 20, 00:00, 4 Years ago
;