Saturday 22 December 2018

Write a program to print all the properties of JavaScript Object

Below function prints all the properties of an object.

function printProperties(object, objectName){
  for(property in object){
    console.log(objectName + "." + property);
  }
}

HelloWorld.js
var employee = {
  "firstName" : "Krishna",
  "lastName" : "Majety",
  "age" : 29,
  "address" : {
    "city" : "Bangalore",
    "area" : "Marthalli"
  }
}

function printProperties(object, objectName){
  for(property in object){
    console.log(objectName + "." + property);
  }
}

printProperties(employee, "employee");

Output
employee.firstName
employee.lastName
employee.age
employee.address

One problem with above function is, it do not print the nested object properties.

For example, employee object has address object in it. Let’s enhance the program to print address object properties also.

HelloWorld.js
var employee = {
  "firstName" : "Krishna",
  "lastName" : "Majety",
  "age" : 29,
  "address" : {
    "city" : "Bangalore",
    "area" : "Marthalli"
  }
}

function printProperties(object, objectName, tab){
  for(property in object){
    console.log(tab + objectName + "." + property); 
    
    if(object[property] instanceof Object){
      printProperties(object[property], objectName+"."+property, "  " + tab);
    }
  }
}

printProperties(employee, "employee", "")

Output
employee.firstName
employee.lastName
employee.age
employee.address
  employee.address.city
  employee.address.area

Let’s further enhance this program to print the value of the object properties.


HelloWorld.js
var employee = {
  "firstName" : "Krishna",
  "lastName" : "Majety",
  "age" : 29,
  "address" : {
    "city" : "Bangalore",
    "area" : "Marthalli"
  }
}

function printProperties(object, objectName, tab){
  for(property in object){
    console.log(tab + objectName + "." + property + " => " + object[property]); 
    
    if(object[property] instanceof Object){
      printProperties(object[property], objectName+"."+property, "  " + tab);
    }
  }
}

printProperties(employee, "employee", "")

Output
employee.firstName => Krishna
employee.lastName => Majety
employee.age => 29
employee.address => [object Object]
  employee.address.city => Bangalore

  employee.address.area => Marthalli


Previous                                                 Next                                                 Home

No comments:

Post a Comment