Objects in javascript

Objects in javascript

Declaration of the object:

In JavaScript, we can create an object by using curly braces {} and then add key-value pairs as items of the object. Key-value pairs are like pairs of name and value. The key is what you will use to access the value, and the value is the data that you want to store in the object. The example is shown below.

const jsUSer = {
    name: "User1",
    email: "user@gmail.com",
    age: 25,
    location: "Mumbai",
    isLoggedIn: false,
}

Accessing the object elements

We can access the Object elements in two ways i.e. with the "." keyword and by using square brackets [], as shown in the example below.

const jsUSer = {
    name: "User1",
    email: "user@gmail.com",
    age: 25,
    location: "Mumbai",
    isLoggedIn: false,
}

console.log(jsUSer.name); //Output: User1
console.log(jsUSer["email"]); //Output: user@gmail.com

Adding new key-value pair and modifying the existing object elements:

You can also add new key-value pairs to an object using square brackets [] as well as by the "." keyword and we can modify the existing values in the same way as shown in the example below.

const jsUSer = {
    name: "User1",
    email: "user@gmail.com",
    age: 25,
    location: "Mumbai",
    isLoggedIn: false,
}
jsUSer.email = "data@data.com" //modifying existing key-value pair with . operator
jsUSer["name"] = "User2"; //modifying existing key-value pair with [] operator

jsUSer.baseLocation = "Delhi" //adding new key-value pair with . operator
jsUSer["occupation"] = "Software Engineer"; //adding new key-value pair with [] operator

console.log(jsUSer);
/* Output: 
{
  name: 'User2',
  email: 'data@data.com',
  age: 25,
  location: 'Mumbai',
  isLoggedIn: false,
  baseLocation: 'Delhi',
  occupation: 'Software Engineer'
}
*/

Freezing the object:

In Javascript, we can restrict the object from any further modification with the help of Freez. Once the user freezes the object then we no longer can modify/add new key-value pairs of an object.

const jsUSer = {
    name: "User1",
    email: "user@gmail.com",
    age: 25,
    location: "Mumbai",
    isLoggedIn: false,
}
jsUSer.email = "data@data.com" //modifying existing key-value pair with . operator
jsUSer["name"] = "User2"; //modifying existing key-value pair with [] operator

jsUSer.baseLocation = "Delhi" //adding new key-value pair with . operator
jsUSer["occupation"] = "Software Engineer"; //adding new key-value pair with [] operator

console.log(jsUSer);
Object.freeze(jsUSer);
jsUSer["role"] = "Test Engineer"; //trying to add new key-value pair after the object is freezed
jsUSer.email = "user@xyz.com" //trying to modify existing key-value pair after the object is freezed 

/* Output: 
{
  name: 'User2',
  email: 'data@data.com',
  age: 25,
  location: 'Mumbai',
  isLoggedIn: false,
  baseLocation: 'Delhi',
  occupation: 'Software Engineer'
}
*/

Adding and accessing the function inside the object

As we can have the key-value pairs in an object the same we can also have a function inside the object. We can declare and access a function inside the object as shown below.

const jsUSer = {
    name: "User1",
    welcomeMessage: "Hello there",
    greetings : function() {
        console.log(`${this.welcomeMessage}, ${this.name} how are you`)
    }
}
console.log(jsUSer.greetings()) //Output: Hello there, User1 how are you

Accessing the nested object elements

In some cases we can find the objects within an object. To access the nested object key-value pairs we can access them by the below way.

const regularUser = {
    email: "some@gmail.com",
    fullName: {
        userFullname: {
        firstName: "user1",
        lastName: "surname"
    }
}
}
console.log(regularUser.fullName.userFullname.firstName); //Output: user1

Combining two objects with the spread keyword:

In Javascript, we can combine two objects with the spread keyword as shown in the below example

const obj1 = { 1:"a",2:"b"}
const obj2 = { 3:"c",4:"d"}
const obj3 = { ...obj1, ...obj2 };
console.log(obj3); //Output: { '1': 'a', '2': 'b', '3': 'c', '4': 'd' }

Combining two objects with the Assign keyword:

The Object.assign() method can be used to merge two objects. The assign method can combine obj1 and obj2 as shown in below example.

const obj1 = { 1:"a",2:"b"}
const obj2 = { 3:"c",4:"d"}
const obj3 = Object.assign({}, obj1, obj2);
console.log(obj3); //Output: { '1': 'a', '2': 'b', '3': 'c', '4': 'd' }

Accessing multiple objects from an array:

In some cases, we can have multiple objects inside an array. To access the object elements inside the array we can make use of [] notation as shown in below example.


//multiple objects inside array how to access
const users = [
    {
        id: 1,
        email: "user1@gmail.com"
    },
    {
        id: 2,
        email: "user2@gmail.com"
    }

]
console.log(users[0].email)// to access first object email
console.log(users[1].id); //to access second object id

object methods:

  1. Object.keys(): The Object.keys() returns an array of all the property names(keys) in an object. The return type of this method is array.

     const users = 
         {
             id: 1,
             email: "user1@gmail.com"
         }
         console.log(Object.keys(users)) //Output: [ 'id', 'email' ]
    
  2. Object.values(): The Object.values() method returns an array of all the values in an object. The return type of this method is array.

     const users = 
         {
             id: 1,
             email: "user1@gmail.com"
         }
         console.log(Object.values(users)) //Output: [ 1, 'user1@gmail.com' ]
    
  3. Object.entries(): The Object.entries() method returns an array of all the key-value pairs in an object. The return type of this method is array.

     const users = 
         {
             id: 1,
             email: "user1@gmail.com"
         }
         console.log(Object.entries(users)) //Output: [ [ 'id', 1 ], [ 'email', 'user1@gmail.com' ] ]
    
  4. Object.hasOwnProperty(): The Object.hasOwnProperty() method returns true or false if the object has the passed property as shown in the below example.

     const users = 
         {
             id: 1,
             email: "user1@gmail.com"
         }
         console.log(users.hasOwnProperty("email")) //Output: true
         console.log(users.hasOwnProperty("occupation")) //Output: false