An object is an excellent data structure in JavaScript. Why it’s awesome? Because it stores data as a key and value as a pair; apart from that every key is unique so we can store unique information inside objects. Now let’s understand, How to implement this data structure, the syntax for an object is –
How to create an object
var obj = {}; // An Empty object
// Or
var obj = new Object();
The basic structure of an object like the below code –
var variabl_name = { 'key_1': value };
var obj = { 'name': 'xyz', 'age': 23 };
How to access the 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
We can not use the dot operator if our key is separated by a hyphen.
obj["stu-name"] = "John"
// Can't use like
obj.stu-name; // Error
How to delete property
To delete a property we can use the delete keyword
delete obj.name;
How to get the length of a javascript object
We will use keys properly
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 write a 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 part of an object like this example –
var obj = {
val: undefined
};
console.log(obj.test); // undefined
console.log("val" in obj); // true
Access all keys with for in loop
We have for keyword to access all key but with the help of in it become easier to use –
for (var o in obj) {
console.log(key, o[key]);
//name xyz
// age 23
}