Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructure object and reassign to different variable name in one go

I have an object:

let obj = {
  "t":
    {
      "en": {
        "head" :"hello",
        "sub"  : "this is great"
      }
    }
  "link": {}
}

and I'm destructuring it:

{ t: { en }}

is it possible to reassign t to en in the same destructuring statement?

So I want the object assigned to en in the variable t not in en

like image 510
supersize Avatar asked Oct 21 '25 14:10

supersize


2 Answers

When you're destructuring an object, you can specify propname: variablename to assign the property to a variable with a different name. Putting just the property name without a variable is equivalent to propname: propname, to use the same name for the variable and property, but you don't need to use that shortcut.

So you can do it like this:

let obj = {
  "t":
    {
      "en": {
        "head" :"hello",
        "sub"  : "this is great"
      }
    }
}

let { t: { en: t } } = obj;
console.log(t);

The first t: is just a property name, it specifies that the value is an object which needs to be destructured as well. In that structure, we use the propname: variablename syntax, so the en property is assigned to the t variable.

In a function definition this would look like:

const Home = ({ t: { en: t }, link}) => console.log(t);

let obj = {
  "t":
    {
      "en": {
        "head" :"hello",
        "sub"  : "this is great"
      }
    }
};
Home(obj);

Note that there's no actual relationship between the two uses of t. The variable can actually be anything, e.g.

const Home = ({ t: { en: blah }, link}) => console.log(blah);
like image 97
Barmar Avatar answered Oct 24 '25 03:10

Barmar


No, it's impossible to reassign t, because t is a const. If t weren't a const, then yes, it would be possible to reassign it:

let t = {
  "en":
    {
      "head": "hello",
      "sub" : "this is great"
    }
};

({ en: t } = t);
console.log(t);

Note that

{ t: <something>

would only be done with destructuring if t were a property of the parent object - but here, t is a standalone variable, not a property so instead, start with

{ en: <something>

with t on the right-hand side.

If t actually is a property of the parent object, then you can do the same sort of thing:

let obj = {
  "t":
    {
      "en": {
        "head" :"hello",
        "sub"  : "this is great"
      }
    },
  "link": {}
};
const { t: { en: t } } = obj;
console.log(t);
like image 21
CertainPerformance Avatar answered Oct 24 '25 03:10

CertainPerformance