working with Objects in Javascript
An object is a collection of properties, where properties are the association between a name (or key) and a value. The value of a property can be a function, in which case the property is known as a method.
JavaScript object has properties associated with it. You can define your own objects, by creating, properties, functions, and methods.
Converting objecjects to string
We can use the The JSON.stringify() method to converts JavaScript objects into strings.
Example:
<script>
var color = {
'red': [255, 0, 0],
'blue': [0, 0, 255],
'green': [0, 0, 255]
}
document.getElementById('demo').innerHTML=JSON.stringify(color);
Output:
// { "red": [ 255, 0, 0 ], "blue": [ 0, 0, 255 ], "green": [ 0, 0, 255 ] }
Get the length/size of the object by the keys ( The keys are all the first element in the objects that comes before the colon (:))
var dSize = Object.keys(color).length;
document.getElementById('demo1').innerHTML=size;
Output:
// 3
Get the length/size of the object by the keys ( The values are all the elements in the objects that comes after the colon (:))
var dSize = Object.values(color).length;
document.getElementById('demo').innerHTML=dSize;
Output:
// 3
</script>
Creating a new object
You can create a new object following the methods below():
Method 1: create an object by declaring the variables once, separated by commas.
var myObj = new Object(),
str , Subject, year;
Then assign values to the keys.
myObj.str = 'hhgg';
myObj[ 'Subject'] = 'Math';
myObj['year'] ='2002'
document.getElementById('demo').innerHTML=JSON.stringify(myObj);
Output:
{"str":"hhgg","Subject":"Math","year":"2002"}
Method 2: create an object by declaring an empty object using the {} symbol
var myObj ={};
Then populate the object with keys and values.
myObj.id=77;
myObj.name='object'
myObj.style='standard'
document.getElementById('demo').innerHTML=JSON.stringify(myObj);
Output:
{"id":77,"name":"object","style":"standard"}
Method 3: create an object and call it with a function from the object
var d_obj = {
Country: 'Nigeria',
Age:String(70) + 'years',
History: function () {
return this.Country + " " + this.Age;
}
}
var details= d_obj.History();
document.getElementById('demo').innerHTML=details;
Output:
Nigeria 70years
Method 4: create an object with existing value, using a constructor
function Car(age, sex, education) {
this.age = age;
this.sex = sex;
this.education = education;
}
Now Create new objects of the object
var employee_1= new Employee(30, 'Male', 'PG');
var employee_2= new Employee(22, 'Female', 'U_GRAD');
Get object employee_2's age
document.getElementById('demo').innerHTML= employee_2.age;
Now Create new property( instance variable) for employee_2
employee_2.experience='Professional'
document.getElementById('demo').innerHTML= employee_2.experience