JavaScript Object - Lecture -11th

JavaScript Object - Lecture -11th

Congratulation guys for making it this far in our journey to become a full-stack web developer.

CONGRATULATION

Today's topic is Objects in JS.

Before understanding the objects let's deep dive into the limitation of the array:-

let's understand it by an example:

Rahul is a user of your website and you need to store his data such as name, email, password, and mobile.

we can add this data to the array as follows

let users= ['name','email','password','mobile']
let data = ['Rahul','rahul@gmail.com','*45Aedas',9641851224]

Suppose now I need to find the password of Rahul, for that first we need to find the index of the password in the employees' array, and then from that index, we can find the password of Rahul.

But is it a good approach?

Suppose a company has 5000 users and we store their data in such a

To address such situations objects were introduced.

What is an Object?

An object is a collection of key-value pairs. The keys are also known as properties, and the values can be any data type, including strings, numbers, arrays, or even other objects.

How to declare an Object?

var details={}

in object the data are stored in key-value pairs

const person = {
  name: "John",
  age: 30,
  job: "software developer",
  hobbies: ["reading", "swimming"]
};

Properties of object

  1. Accessing the value

    Dot Notation

    Syntax

     object.key
    
    const person = {
      name: "John",
      age: 30,
      job: "software developer",
      hobbies: ["reading", "swimming"]
    };
    
    person.name //John
    person.age //30
    person.job //software developer
    person.hobbies  //  ["reading", "swimming"]
    person.hobbies[0]  //  reading
    

    Bracket Notation

    Syntax

     object["key"]
    
    const person = {
      name: "John",
      age: 30,
      job: "software developer",
      hobbies: ["reading", "swimming"]
    };
    
    person['name'] //John
    person['age'] //30
    person['job'] //software developer
    person['hobbies']  //  ["reading", "swimming"]
    person['hobbies'][0]  //  reading
    
  2. Adding new key

    1. Dot Notation

      object.key=value
      
      var employees = {
      Rahul:'1,00,000',
      Suraj:'4,00,000',
      Ashutosh:'5,00,000',
      John:'1,00,000'
      }
      
      //To add new employee we can do 
      employees.Nishant='2,00,000'
      
      console.log(employees) 
       /*{Ashutosh: "5,00,000".
      John: "1,00,000",
      Nishant: "2,00,000",
      Rahul: "1,00,000",
      Suraj: "4,00,000"}*/
      
    2. Bracket Notation

      object['key']=value
      
      var employees = {
      Rahul:'1,00,000',
      Suraj:'4,00,000',
      Ashutosh:'5,00,000',
      John:'1,00,000'
      }
      
      //To add new employee we can do 
      employees['Nishant']='2,00,000'
      
      console.log(employees) 
       /*{Ashutosh: "5,00,000".
      John: "1,00,000",
      Nishant: "2,00,000",
      Rahul: "1,00,000",
      Suraj: "4,00,000"}*/
      
  3. Deleting a key

    var employees = {
    Rahul:'1,00,000',
    Suraj:'4,00,000',
    Ashutosh:'5,00,000',
    John:'1,00,000'
    }
    delete employees.Rahul   // it will delete rahul key
    delete employees['Suraj']  // it will delete rahul key
    

loops in object

The object cannot be iterated with a normal for loop as an object doesn't have an index as numbers. so to iterate objects we have a special loop that is for in loop.

const person = {
  name: "John",
  age: 30,
  job: "software developer",
  hobbies: ["reading", "swimming"]
};

for(let key in person){
// Keep in mind here you need to use box notation.
// also do console.log(key)

console.log(person[key])

}

Arrays Inside Object

we can store an array inside objects as well.

let detail = {
      title: "FB 3-Day: 3 Workouts Per Week for 2 Weeks",
      price: "7.99",
      difficultyLevel: [ 3,4],
      bodyFocus: "Total Body",
      equipmentData: ["Dumbbell", "Mat" ],
      trainingTypeData: ["Strength Training"]}

as in the above example, we have stored an array in an object.

we can store any data structure and data type as a value in an object such as a number, boolean, string, bigInt, array, and object as well.

Even we can store functions as well in the value part which we will learn about in the next session.

The object inside the object (Nested Object)


let school = {
  class11: {
      rahulMarks:  { english: 99, hindi: 100, maths: 70 },

  },
};
// to access the marks of english
school['class11']['rahulMarks']['english']

Assignment

  1. create an object with five names as keys and give them a value.

    print all the keys using for in loop.

  2. You are given a variable

    let str='asdnbknsadknsadnjk'
    

    To make an object using a loop that will give the key as the character and the value as a number of characters.

    Sample Input

    let str='saaslaa'

    Sample output

    {a:4,s:2,l:1}

  3. Write a function countProperties that takes an object as an argument and returns the number of properties (key-value pairs) in the object.

  4. Write a function getPropertyNames that takes an object as an argument and returns an array of all the property names (keys) in the object.

  5. Write a function getPropertyValues that takes an object as an argument and returns an array of all the property values (values) in the object.

  6. Write a function sumValues that takes an object as an argument and returns the sum of all the values in the object.

  7. Write a function averageValue that takes an object as an argument and returns the average of all the values in the object.

  8. Write a function findLargestValue that takes an object as an argument and returns the largest value in the object.

  9. Write a function findSmallestValue that takes an object as an argument and returns the smallest value in the object.

  10. Write a function reverseProperties that takes an object as an argument and returns a new object with the keys and values reversed (i.e. the keys become the values and the values become the keys).

  11. Write a function findLongestKey that takes an object as an argument and returns the longest property name (key) in the object.

  12. Write a function swapProperties that takes an object as an argument and returns a new object with the keys and values of the original object swapped (i.e. the values become the keys and the keys become the values).

Did you find this article valuable?

Support Nakul Goel by becoming a sponsor. Any amount is appreciated!