3

Is there a one-liner to do this that I'm blanking on?

// this.state is a basic object with many keys
var {toDate, fromDate, location, flavor} = this.state
var goodKeys = {toDate, fromDate, location, flavor}
// goodKeys is an object that contains a subset of this.state's keys

The only way I can think of is:

var {keyIDontWant, otherUnwanted, ...goodKeys} = this.state

But this seems like it would be confusing to people reading the code, and take more effort to figure out how to write.

Balls McHenry
  • 279
  • 3
  • 11
  • 2
    The question is tagged with `ecmascript-6`, object rest spread isn't a part of ES6 and isn't standardized yet. Omitting known 'bad' keys with `{keyIDontWant, otherUnwanted, ...goodKeys}` doesn't make the rest of the keys 'good'. – Estus Flask Sep 02 '16 at 19:22
  • 1
    This has been asked a number of times. The answer is NO. –  Sep 02 '16 at 19:23
  • The state of the art is still `goodKeys = {toDate: this.state.toDate, ...};`. –  Sep 02 '16 at 19:31

1 Answers1

1

_.pick is still one of Underscore/Lodash features that have their use cases in ES6.

ES6 one-liner may be an IIFE and will result in enumerating the list of properties twice:

let goodKeys = (
  ({toDate, fromDate, location, flavor}) => ({toDate, fromDate, location, flavor})
)(this.state);

ES.next one-liner counterpart to _.pick may involve Object.entries:

Object.entries(o)
.filter(([key]) => ['toDate', 'fromDate', 'location', 'flavor'].includes(key))
.reduce((obj, [key, val]) => Object.assign(obj, { [key]: val }), {});
Estus Flask
  • 150,909
  • 47
  • 291
  • 441
  • Although the ES6 one-liner is admittedly awkward, and makes one desperately wish for a language feature such as [extended dot notation](https://github.com/rtm/js-pick-notation/blob/master/minimal/spec.md), at least in a typed environment it is type-checkable, unlike `_.pick` or roll-your own variants thereof, which involve passing around property names as strings. –  Sep 02 '16 at 20:29