Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unpacking fields from nested objects passed as a parameter

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} `;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading