Javascript Advanced Object Operations with examples
You may consider an object as a kind of class which has data members and member functions. In this section, I’ll be showing you performing some useful operations using objects.
Checking object has items
Like arrays, the object doesn’t have length
a property to check if items exist. But their other way around we can use javascript built-in Object
Class. This function provides many properties and method we can call on our created object and that is Object.keys()
a method.
The Object.keys()
method returns keys or object indexes in the form of array items on this we can call length
property.
var person = {"name" : "Sam", "age" : 25}; console.log(person); if(Object.keys(person).length > 0){ console.log("Items exists in person Object"); }else{ console.log("Items does not exists in person Object"); } //Console Output {name: "Sam", age: 25} Items exists in person Object
Applying Object.keys()
method on an empty object.
var car = {}; console.log(car); console.log(Object.keys(car)); Object.keys(car).length; //Console Output {} [] 0
Functions in objects
The function can be added into objects the same way we insert items. Adding function on object initialization.
var person = { "first_name" : "Jake", "last_name" : "Daniels", "age" : 24, "get_full_name" : function(){ return this.first_name+" "+this.last_name; } }; console.log("Person "+person.get_full_name()+" is "+person.age+" years old"); //Console Output Person Jake Daniels is 24 years old
get_full_name
is a method of Object Person
to create a function in the object we declare function followed by brackets which hold argument list.
In this particular object, case function does not take any arguments. Inside the function, we are returning a person’s first_name
and last_name
.
You can notice insisted of calling first_name
and last_name
in get_full_name()
method we use this
word followed by property.
So this
is a javascript object calling this
inside Person
refers to that Object itself.