2

I have multiple cases throughout my app that look something like this:

  getVariables() {
    const {
      allowCustomValues,
      budgets,
      budgetsToAdd,
      budgetsToRemove,
      isGlobal,
      isRequired,
      name,
      tagTypeId,
      valuesToAdd,
      valuesToDelete,
    } = this.props;

    return {
      allowCustomValues,
      budgets,
      budgetsToAdd,
      budgetsToRemove,
      isGlobal,
      isRequired,
      name,
      tagTypeId,
      valuesToAdd,
      valuesToDelete,
    };
  }

This seems very cumbersome, but the shorter solution involves preceding every variable I want with this.props., which isn't really better from a maintenance standpoint.

What I'd like is something like:

  getVariables() {
    return this.props.{
      allowCustomValues,
      budgets,
      budgetsToAdd,
      budgetsToRemove,
      isGlobal,
      isRequired,
      name,
      tagTypeId,
      valuesToAdd,
      valuesToDelete,
    };
  }

Is there some kind of ES6 syntax that allows me to make this code a bit more DRY?

EDIT: Possibly a duplicate of ES6 destructuring within a return statement, but that one has an accepted answer that doesn't solve the problem.

Ecksters
  • 1,150
  • 1
  • 10
  • 23

3 Answers3

3

Actually destructuring does not allow that.

You are asking about equivalent for lodash's pick(). Maybe you have already lodash in you project. If you don't you still can write such a helper on your own(but better use stable community-proved versio from lodash or another library)

skyboyer
  • 15,149
  • 4
  • 41
  • 56
  • Well, this is actually a very good answer, as we do have Lodash, thanks! – Ecksters Oct 03 '18 at 20:55
  • It's probably worth noting, however, that this method isn't going to get checked by a linter, and is much less efficient due to the creation of so many string literals. – Ecksters Oct 03 '18 at 21:10
  • But it's not exactly lodash's pick() because using pick you still have to repeat yourself, both while destructing each prop + assigning all props to a single var. – RegarBoy Aug 07 '20 at 18:55
  • @RegarBoy not sure about _your_ case, OP asked to destructure object only to return smaller subset of keys. Sure, if you need to do additional operations with every or some properties, `_.pick` will not be enough. – skyboyer Aug 07 '20 at 22:15
2

Why not just use Object.assign()?

    return Object.assign({}, this.props);

That'll build a new empty object and then copy all the enumerable properties from this.props into it. The target object is returned by Object.assign() so it pretty much does all the work.

Pointy
  • 371,531
  • 55
  • 528
  • 584
1

How about

return {...this.props}

Martin
  • 5,236
  • 4
  • 35
  • 60
  • What if I don't want all of the props, just specific ones? That's the entire point of destructuring. – Ecksters Oct 03 '18 at 20:43