Skip to content
Advertisement

One-liner to take some properties from object in ES 6

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?

JavaScript

Advertisement

Answer

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.

JavaScript

(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):

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement