Lambdaphile
Lambdaphile

Reputation: 152

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?

Upvotes: 1

Views: 79

Answers (2)

hgb123
hgb123

Reputation: 14891

You could do an inline style using Immediately Invoked Function Expression

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

const copyObj = { ...(({ a: x, b: y, c: z }) => ({ x, y, z }))(obj) }

console.log(copyObj)

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386654

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);

Upvotes: 2

Related Questions