ES6 - Clone an object and rename its keys in one line?

Viewed 1027

Is there a way to destructure or clone an object into another one, renaming it's keys in the process ?

Example :

let getUser = () => { return {first: "Radio", last: "Reve"} }
let {first: firstName, last: lastName} = getUser()

let o = {firstName: firstName, lastName: lastName} // This is the line I don't wanna have to write

Is there an easy way to have the result stored in an object instead of two distinct variables, firstName and lastName ?

I receive an object from the server with 10 keys, and I would like to pick only 2 keys, and rename those keys, with no extra libraries nor using a special function in a native a consistent way.

1 Answers

It's not currently possible from what I searched using native language syntax, as far as I can tell.

I came up with a general solution that may help:

let cloneAndRename = (obj, renames) => {
    let clone = {};
    Object.keys(obj).forEach(function (key) {
        if (renames[key] !== undefined) {
            clone[renames[key]] = obj[key];
        } else {
            clone[key] = obj[key];
        }
    });
    return clone;
}

Use it like this:

let o = cloneAndRename(getUser(), {first: 'firstName', last: 'lastName'});
Related