Loop in object with for in loop - 09

Object with for-in loop:

const obj = {
      Bangladesh: "Dhaka",
      India: "New Delhi",
      Pakistan: "Islamabad",
      Srilanka: "Colombo",
      Nepal: "Kathmandu",
      Bhutan: "Thimphu",
};


for (const key in obj) {
      // Here key will return the key from the object
      console.log(key);

      // --- Result: ---
      // Bangladesh
      // India
      // Pakistan
      // Srilanka
      // Nepal
      // Bhutan

      // This will return the values from the object
      console.log(obj[key]);

      // --- Result: ---
      // Dhaka
      // New Delhi
      // Islamabad
      // Colombo
      // Kathmundu
      // Thimpu
}

// values() method will extract the values and
// return an array of the values
console.log("VALUES ===> ", Object.values(obj));

// keys() method will extract the keys and
// return an array of the keys
console.log("KEYS ===> ", Object.keys(obj));

Post a Comment

Previous Post Next Post