Wednesday, June 13, 2018

JavaScript - Object Notation - accessing values

Below code demonstrates usage of JavaScript Object Notation:

// declaring a javascript object
var person = {
  name: "MS Dhoni",
  city: "Ranchi",
  team: "Chennai Super Kings",
  details: {
    hobbies: ["cooking","cricket","chess"],
    location: "India"
  },
  greeting: function() {
  console.log("welcome");
}
}

// Printing the person object to console
console.log(person);

// Printing the person name to console
console.log(person.name);

// Printing the person name using dictionary notation. 
// This technique can be used to access the field name dynamically
field = "name"
console.log(person[field]);

//accessing deeper levels 
console.log(person.details.hobbies);

// accessing deeper levels dynamically
console.log(person["details"]["hobbies"]);

// calling the function defined inside the object
person.greeting();


Practice athttp://jsbin.com

No comments:

Post a Comment