Home > Blockchain >  I'm trying to extract the values of an object using destructuring assignment, the age variable
I'm trying to extract the values of an object using destructuring assignment, the age variable

Time:05-18

const obj = {
  firstUser: {
    name: {
      firstName: 'John',
      lastName: 'Doe',
    },
    age: 32,
  }
}

const {
  firstUser: {
    name: {
      lastName: Lname
    }
  },
  age
} = obj;

console.log(Lname);
console.log(age);

CodePudding user response:

Try this way:

const { firstUser } = obj;
const { name, age } = firstUser;
const { lastName: Lname } = name; // this is destructuring assignment

Now you can use lastName as Lname variable.

CodePudding user response:

Because you have placed the age field inside firstName object,nested inside the obj. I have refactored your code

 const obj = {
  firstUser: {
    name: {
      firstName: 'John',
      lastName: 'Doe',
    },
  },
  age: 32,
}


const {firstUser:{name: {lastName: Lname}}, age} = obj;

console.log(Lname);
console.log(age);

  • Related