paint-brush
Quick Guide to JavaScript Objectsby@dhavalleela85
283 reads

Quick Guide to JavaScript Objects

by Dhaval LilaFebruary 28th, 2019
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Simply put, an object is a nothing but collection of keys and corresponding values. Let’s take an example of my favorite character from Simpsons :
featured image - Quick Guide to JavaScript Objects
Dhaval Lila HackerNoon profile picture

Simply put, an object is a nothing but collection of keys and corresponding values. Let’s take an example of my favorite character from Simpsons :

const obj = {

"name": "Homer Simpson",

"gender": "Male",

"children": ["Lisa","Bart"]//oops homer forgot the Maggie again DOH!

}

Now the question is how do you access the values? answer is as simple as it could be. Below is the output of various console logs :


console.log(obj.name)>>"Homer Simpson"


console.log(obj.gender)>> "Male"


console.log(obj.children)>>["Lisa" , "Bart"]


console.log(obj.children[0])>>"Lisa"

Essentially object.key will give you value of that key. You can also access the value of name by bracket notation:obj["name"] and it will give the same result as dot notation:obj.name.

Creating new object

There are many ways to create objects but sake of keeping this guide simple we are only going to discuss two ways to an create objects.

First is by just using curly bracket like shown above:

const obj = {

"name": "Homer Simpson",

"gender": "Male",

"children": ["Lisa", "Bart"]

}

Second is by using new keyword:

function Person(name,gender,children) {  this.name = name;  this.gender = gender;  this.children = children}const obj = new Person("Homer Simpson","Male",["Lisa","Bart"])

Adding new key :

Now let’s add new key to our object:


obj.wife = "Marge Simpson"console.log(obj)

>> {

"name": "Homer Simpson",

"gender": "Male",

"contact no": "123456789012",

"children": ["Lisa", "Bart"],

"wife" : "Marge Simpson"

}

You can also set functions as values of any key. The name of key can be anything that is a string or that can be converted to string. We can also delete any key of objects using delete obj.key or delete obj["key"].

Enumerate the keys of an object :

If you don’t know the keys and you want to access the objects then you can iterate through keys using object.keys(obj) . object.keys(obj) will give you array of keys and then you can call forEach() and iterate through key. below is the example of that

Object.keys(data).forEach( (element) => {

console.log(obj\[element\])

})





output :>>"Homer Simpson">>"Male">>["Lisa","Bart"]>>"Marge Simpson"

That’s all folks!!!

Here is some random programming humor to cheer up your day