Home > Software design >  Unpacking fields from nested objects passed as a parameter
Unpacking fields from nested objects passed as a parameter

Time:11-10

How can I unpack nested object passed as a parameter? I want to unpack age from the object how can I do that?

const user = {
  id: 42,
  username: "usrname",
  info: {
    fullName: "John",
    age: 15
  }
};

function foo({ username: usrnam, info }) {
  return `${usrnam} ${info} `;
}

CodePudding user response:

You can destructure any level as:

{ username: usrnam, info: { age } }

or, if you don't want to assign to a new variable name then:

{ username, info: { age } }

const user = {
  id: 42,
  username: "usrname",
  info: {
    fullName: "John",
    age: 15,
  },
};

function foo({ username: usrnam, info: { age } }) {
  return `${usrnam} ${age} `;
}

console.log(foo(user));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related