Skip to content
Advertisement

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

Advertisement

Answer

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));
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement