Search code examples
ecmascript-6destructuring

ES6 destructuring/cloning a subset of an object


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?


Solution

  • 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}