Home > Blockchain >  How to use console.log to get a specific value of an object in nested objects
How to use console.log to get a specific value of an object in nested objects

Time:02-05

const businessInfo = {
  firstName: "Fred",
  lastName: "Stone",
  company: {
    name: "Software Solutions",
    jobTitle: "Chief Technology Officer",
  },
  employee: [
    {
      firstName: "Pete",
      lastName: "Perkins",
      department: {
        name: "Front End",
        jobTitle: "Junior Developer",
      },
    },
    {
      firstName: "Jack",
      lastName: "Steel",
      department: {
        name: "Back End",
        jobTitle: "Senior Developer",
      },
    },
  ],
};

With console.log, I want to access name: "Front End", jobTitle: "Junior Developer" within department for Pete. I figure I need at least console.log(businessInfo.employee) but I am stuck beyond that.

CodePudding user response:

You can access name and jobTitle property like this

console.log(businessInfo.employee.department.name);
console.log(businessInfo.employee.department.jobTitle);

CodePudding user response:

I found out the following solutions work:

  console.log(businessInfo.employee[0].department);
  console.log(businessInfo['employee'][0]['department']);
  console.log(businessInfo["employee"][0]["department"]);
  •  Tags:  
  • Related