Search code examples
javascriptecmascript-6javascript-objectsdestructuring

JS: Destructure an object into another with renamed properties


Is it possible to do something like the following in JS?

const obj = { a: 1, b: 2, c: 3 };

const copyObj = {...{ a: x, b: y, c: z } = obj };

I'm aware that I can do this:

const { a: x, b: y, c: z } = obj;

const copyObj = { x, y, z };

but it's not what I want. Any suggestions?


Solution

  • You could take a function for getting wanted and renamed properties.

    const
        rename = ({ a: x, b: y, c: z }) => ({ x, y, z }),
        obj = { a: 1, b: 2, c: 3 },
        copyObj = rename(obj);
    
    console.log(copyObj);