Skip to content

09 Object

Biswajit Sundara edited this page May 1, 2023 · 2 revisions

Objects are variables too but it has a group of values. Usually we group relevant values and call it as object. Every object has properties and values for them. For example, a car object will have name, model, weight, color etc.

Simple Object

const person = {
    name: "Biswajit",
    age: 32,
    gender:"male"
};

console.log(person);  //sometimes it will return object so use JSON.stringify
console.log(JSON.stringify(person));
console.log(person.name);
console.log(Object.values(person));

Nested Object

let citizen = {
    name: "Priyanka",
    adhar: 56523134,
    address : {
       firstLine: "10 Park Street",
       stateCode: "IL",
       zipCode: "2130"
    }
};

console.log(citizen);

Enhanced Object Properties

We can pass the values for the properties to an object and use it later. Here we have used the same name of the property in the parameter so instead of name:name we can also say just name

const calculator = (name) =>{
   return {
       //name:name
       name,
   }
}
const calc = calculator("casio");
console.log(calc.name);

Object with methods

Methods are like actions of an object. For example, car object can have action for start(), drive(), stop() etc. Here instead of add:function(n1,n2) we are directly giving add(n1,n2) both are correct.

const calculator = (name) =>{
   return {
       //name:name,
       name,

       //add: function(n1,n2){
       add(n1,n2){
           return n1+n2;
       }
   }
}

const calc = calculator("casio");
console.log(calc.name);
console.log(calc.add(2,2));

Fetching Object Values

If we want to fetch values from object using the field name as key.

function getUser(key) {
    let user = {
        uname: 'Biswajit',
        age: 21
    }
 console.log(user[key]);
}

getUser('age');

Create Dynamic Objects

We can create objects during run time with dynamic key and property values.

const actors = ['Sahrukh','Akshay','Ajay','Saif'];
const wives = ['Gauri','Twinkle','Kajol','Kareena'];
const coupleObj = {};
let i=0;
actors.forEach((actor)=>{
    coupleObj[actor]= wives[i];
    i++;
});

console.log(coupleObj);
console.log(coupleObj.Sahrukh);

Filter Object Array

We can filter the object array based on a condition.

const persons = [
    {
      name: "John",
      age: 30,
      gender: "male",
    },
    {
      name: "Jenny",
      age: 20,
      gender: "female",
    },
    {
      name: "Shawn",
      age: 40,
      gender: "male",
    },
  ];

  const females = persons.filter((person) => {
    return person.gender == "female";
  });

  console.log(females);

Clone this wiki locally