3

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.

Radioreve
  • 3,173
  • 3
  • 19
  • 32
  • `var copy = Object.assign({},getUser())` – Redu Sep 26 '17 at 12:21
  • Not really a duplicate. I added comments to clarify what I want – Radioreve Sep 26 '17 at 12:28
  • @Radioreve It is still a duplicate. See the first answer: "In other words, there is no way to "deconstruct from an object into an object", or "pick from an object into an object". You can only deconstruct from an object into variables." – str Sep 26 '17 at 12:30
  • @str alright indeed. So it's not possible... *sad face* – Radioreve Sep 26 '17 at 12:32
  • 1
    You can shorten that line to `{firstName, lastName}`, but indeed there's no other way than to explicitly construct the object – Bergi Sep 26 '17 at 12:34

1 Answers1

1

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'});
Aman Singh
  • 934
  • 9
  • 16
  • not quite what I wanted, but thanks though :) it seems it's not possible with a basic one liner and language constructs.. yet at least ! – Radioreve Sep 26 '17 at 12:34
  • Updated my answer to say that it may not be able to be done using basic syntax just yet. However, the logic of the solution is still fine. – Aman Singh Sep 26 '17 at 12:37