Theory
JavaScript objects are powerful data structures that allow related data to be organized into a coherent whole.
They are used in everyday life and we can encounter them in various ways.
- E-commerce – Online stores use objects to represent products, which have properties such as name, price, stock status, description, category, etc.
- Hotel reservations – Hotels use objects to represent reservations, where each reservation object can contain data such as customer name, dates, room type, price calculations, etc.
- Cars – Each car can be an object with various attributes such as make, model, color, engine size, registration number, etc.
- Students – Each student could be an object with attributes such as name, age, class, grades, attendance, activities, etc.
Creating an object
let auto = {
mark: "Dodge",
mudel: "Challenger",
aasta: 2013,
varv: "Sinine",
omadused: ["kliimaseade", "elektriaknad", "navigatsioonisüsteem"]
};
console.log(auto);


You can access the properties of each object using dot syntax. You can access the properties of each object using dot syntax. You can access the properties of each object using dot syntax.
console.log(auto.mark); // Output: "Dodge"
console.log(auto.mudel); // Output: "Challenger"
console.log(auto.aasta); // Output: 2013
console.log(auto.varv); // Output: "Sinine"
console.log(auto.omadused); // Output: ["kliimaseade", "elektriaknad", "navigatsioonisüsteem"]


Object methods and using this
Objects in JavaScript can contain not only properties, but also methods. Methods are functions of an object that can manipulate the object’s properties or perform other operations in the context of the object. The keyword this is used within methods to refer to the object in which the method is called.
let auto = {
mark: "Dodge",
mudel: "Challenger",
aasta: 2013,
varv: "Sinine",
omadused: ["kliimaseade", "elektriaknad", "navigatsioonisüsteem"],
//meetodid
taisnimi: function() {
return this.mark + " " + this.mudel;
}
};
console.log(auto.taisnimi());

Abbreviation of the method
The new Javascript ES6 now allows the method to be written more concisely.
//meetodid
taisnimi() {
return this.mark + " " + this.mudel;
}
If the properties are in an array, use a for or forEach loop.
let auto = {
mark: "Dodge",
mudel: "Challenger",
aasta: 2013,
varv: "Sinine",
omadused: ["kliimaseade", "elektriaknad", "navigatsioonisüsteem"],
//meetodid
taisnimi() {
return this.mark + " " + this.mudel;
},
kuvaOmadused() {
this.omadused.forEach(omadus => console.log(omadus));
}
};


Object arrays
An object array is a data structure in JavaScript that consists of multiple objects arranged in order based on an index.
- Each object is a collection of key-value pairs, where the key is unique and the value is the data of the key-value pair.
- An array of objects can contain various data types, including text (strings), numbers, boolean values, functions, other objects, etc.
Creating and displaying an array of objects
Each car is represented as an object containing information about the car’s make, model, and year of manufacture.
let autod = [
{ mark: 'Dodge', mudel: 'Challenger', aasta: 2013},
{ mark: 'Fiat', mudel: '500e', aasta: 2015},
{ mark: 'KIA', mudel: 'EV9', aasta: 2024}
];
console.log(autod);


If you need data about a specific car, you must write its location in the array.
console.log(autod[0]);


And in this object, I can access the elements using “dot syntax,” as above.
console.log(autod[0].mark);


To view all models, we again use the forEach loop
let autod = [
{ mark: 'Dodge', mudel: 'Challenger', aasta: 2013},
{ mark: 'Fiat', mudel: '500e', aasta: 2015},
{ mark: 'KIA', mudel: 'EV9', aasta: 2024}
];
autod.forEach((auto) => {
console.log(`
Mark: ${auto.mark},
Mudel: ${auto.mudel},
Aasta: ${auto.aasta}`);
});


Object array methods
JavaScript array methods can be used with both regular arrays and object arrays. Methods such as push(), pop(), shift(), unshift(), splice(), slice(), forEach(), map(), filter(), reduce(), sort(), etc.
let autod = [
{ mark: 'Dodge', mudel: 'Challenger', aasta: 2013},
{ mark: 'Fiat', mudel: '500e', aasta: 2015},
{ mark: 'KIA', mudel: 'EV9', aasta: 2024}
];
//Lisab uue objekti massiivi lõppu
autod.push({ mark: 'Lexus', mudel: 'LC', aasta: 2016 });
autod.unshift({ mark: 'Mercedes-Benz', mudel: 'E Class', aasta: 1996 });


The splice method simultaneously deletes and adds.
massiiv.splice(
{start indeks},
{mitu eemaldada},
{mida lisada}
);
Searching for a mass
To search for objects in an array, use the find method, which requires a function to be executed. We use the arrow function, which is shorter.
//Otsimine
let otsing = autod.find(auto=>auto.aasta > 2019);
console.log(otsing);


This method searches for the first match and returns it. If no match is found, undefined is displayed. To set multiple conditions, use “&&”.
//Otsimine
let otsing = autod.find(auto=>auto.aasta > 2019 && auto.mark === "Fiat");
console.log(otsing);


Not found, as the only car in 2024 does not match the parameter mark – Fiat
Filtering an array
Instead of getting only one result with find, you can use the filter method to get multiple responses. Filter creates an array from an array and outputs the elements that match the conditions.
Example:
- Let’s assume that we have numbers and we need to get even numbers from them.
let arvud = [1, 11, 3, 4, 16, 6, 7, 19, 9, 20];
const filtreeritud = arvud.filter(arv => arv % 2 === 0);
console.log(filtreeritud);


When used in relation to cars, for example, we can turn to auto.year and filter those manufactured after 2019.
//Filtreerimine
let filter = autod.filter(auto=>auto.aasta > 2019);
console.log(filter);


Sorting an array
The sort method, simple sorting of an array of objects, does not work correctly. Therefore, it is better to use the compare function.
autod.sort((a, b) => a.aasta - b.aasta);
console.log(autod);


Here, (a, b) => a – b is a comparison function that tells sort() to sort numbers by their actual numerical values rather than their string values. The function a – b returns a negative value if a is less than b, a positive value if a is greater than b, and 0 if a and b are equal – exactly what sort() needs to sort its elements correctly
Task
Book object
let raamat = {
pealkiri: "The Song of Achilles",
autor: "Madeline Miller",
aasta: 2021
};
- Add a method that displays the book description.
vastus.innerHTML +="<h2>Ühe raamat</h2>";
vastus.innerHTML +="<p><strong>"+raamat.pealkiri + "</strong> – " + raamat.autor + " (" + raamat.aasta + ")</p>";
- Add a method that changes the year of publication and prints the results to the console.
function muudaAasta() {
raamat.aasta = 2023;
console.log("Uus aasta", raamat.aasta);
return raamat.aasta;
}
muudaAasta();
Library
- Create an object library whose property is books (an array of books).
let raamatukogu =[
{
pealkiri: "Tõde ja õigus",
autor: "A. H. Tammsaare",
aasta: 1926
},
{
pealkiri: "Rehepapp",
autor: "Andrus Kivirähk",
aasta: 2000
},
{
pealkiri: "Minu Eesti",
autor: "Epp Petrone",
aasta: 2009
}
];
console.log(raamatukogu);
- Add a method that displays all books nicely in the console.
raamatukogu.forEach(function(r) {
vastus.innerHTML +="<p><strong>" + r.pealkiri + "</strong> – " + r.autor + " (" + r.aasta + ")</p>";
});
- Add a method that adds a new book.
function lisaRaamat() {
raamatukogu.push({ pealkiri: "Minu raamat", autor: "Timur Basirov", aasta: 2024 });
console.log("Lisatud minu raamat");
}
lisaRaamat();
- Add a method that displays the total number of books in the library.
vastus.innerHTML +="<h2>Raamatukogus on "+raamatukogu.length+" raamatut</h2>";
- Add a method that calculates how many books have been published since 2000.
function raamatudParast2000() {
let uus = raamatukogu.filter(function(r) {
return r.aasta > 2000;
});
return uus;
}
let filtritud = raamatudParast2000();
vastus.innerHTML += "<h2>Raamatud pärast 2000. aastat (" + filtritud.length + " tk)</h2>";
- Develop your own method and write down what it means.
function otsiAutoriJargi(autorNimi){
let leitud = raamatukogu.filter(function(r) {
return r.autor === autorNimi;
});
console.log("Leitud autor:",autorNimi,leitud.length, "raamatut");
vastus.innerHTML +="<h2>Otsing autorilt:"+ autorNimi +" ("+ leitud.length + " raamatut)</h2>";
leitud.forEach(function(r) {
vastus.innerHTML +="<p><strong>" + r.pealkiri + "</strong> – " + r.autor + " (" + r.aasta + ")</p>";
});
}
otsiAutoriJargi("Timur Basirov");
