2

I'm still getting used to destructuring in ES2015/ES6 and wondered if there's a nice way to clone certain keys of an object using it. It's a little hard to explain in words so I'll let the code do the talking. Here's a simplified version of what I have at the moment:

const objectWithLoadsOfData = {
  a: 'a',
  b: 'b',
  c: 'c',
  d: 'd'
};

const objectWithDataSubset = {
  a: objectWithLoadsOfData.a,
  b: objectWithLoadsOfData.b
}

It works, but it seems like it could be simplified with destructuring somehow. Potentially something like:

const objectWithDataSubset = objectWithLotsOfData {a, b};

Obviously this is invalid, but is there something like this that exists?

Sam Beckham
  • 1,188
  • 1
  • 11
  • 23

1 Answers1

1

I am not aware of a functionality that works exactly the way you describe it.

However, with ES6 you can use a shorter notation where the name of the key equals the name of the variable that holds the value, i.e. {a: a, b: b} is equivalent to {a, b}.

const {a, b} = objectWithLotsOfData;
const objectWithDataSubset = {a, b}
TimoStaudinger
  • 34,772
  • 13
  • 76
  • 86
  • I never thought about using left hand assignments, that's not a bad workaround. It gets pretty hefty once you start using proper data but this is probably the right answer. – Sam Beckham Nov 09 '16 at 16:25