Search code examples
ecmascript-6destructuring

Is it possible to destructure an object and generate a new object in a single statement?


const {name, slug, description, parent} = cat;
const saneCat = {name, slug, description, parent};

In the first expression, we define four constants by destructuring a messy object. In the second expression, we combine them into a new object. I would like to do this in a single step without duplicating the list of interesting fields, but because the first expression doesn't define an object, this seems to be impossible. Is it really? We are so close to a Clojurian win!

I have tried the following without success. Any ECMAScript compiler is fair game, but I don't have the option of just using Clojurescript.

const saneCat = {name, slug, description, parent} = cat; // name is not defined
const {...saneCat} = {name, slug, description} = cat;  // name is not defined
const saneCat = ({name, slug, description, parent} = cat); // name is not defined
const saneCat = ({name, slug, description, parent}) = cat; // name is not defined
const saneCat = {{name, slug, description, parent}} = cat; // unexpected token
const saneCat = {{name, slug, description, parent}} = {cat}; // unexpected token

Solution

  • Unfortunately, destructuring in ES6 is limited to assignments and parameter lists. There is a discussion of a "pick" operator which would do what you want, but don't hold your breath.

    Meanwhile, the closest you can come is the following, which requires duplicating the list of properties:

    const saneCat = 
      (({name, slug, description, parent}) => 
        ({name, slug, description, parent})
      )(cat);
    

    Using the proposed pick syntax, you would be able write

    const saneCat = {name, slug, description, parent} # cat;
    

    Something like that should show up in ES29. Until then, you can use pick utilities of the sort mentioned in the comment, but personally, I hate writing properties as strings.

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