Hidden power of javascript object

An object is an awesome data structure in JavaScript. Why it’s awesome? Just because of its store data as key and value pair and every key is unique so we can store unique information inside objects. So one question arises in our mind how to use this, so the syntax for an object is –


var variabl_name = { 'key_1': value };

var obj = { 'name': 'xyz', 'age': 23 };

How to access property

Here we have to way to access the property of an object


obj.propertyname // using dot
Or
obj[propertyname] // using bracket 

/* Like - */

obj.name // "xyz"
Or
obj["name"] //name

How to delete property

To delete a property we can use delete keyword


delete obj.name;

How to get length of javascript object

We will use keys property


var obj = { name: "xyz", age: 23 };

console.log(Object.keys(obj), " and length will be ", Object.keys(obj).length);

// ["name", "age"] and length will be 2

Object tricks

A lot of time we want to access or set dynamic key and we don’t know about that key so how we can access that property?


let key = prompt("what information you want to know about user?", "name");
console.log(obj[key]); // xyz

Instead of name:name we can just write name, like this:


function dummyObj(name, age) {
  return {
    name: name,
    age: age
    // ...other properties
  };
}

var obj = makeUser("xyz", 30);
console.log(obj.name); // xyz

Power of in keyword

Supposed that you have a condition and you want to check key is the part of an object like this example –


var obj = {
val: undefined
};

console.log(obj.test); // undefined
console.log("val" in obj); // true

Access all key with for in loop

We have for the keyword to access to all key but with the help of in it become more easy to use –


for (var o in obj) {
     console.log(key, o[key]); 
     //name xyz
     // age 23
}

You May Also Like

About the Author: Pankaj Bisht