Looping over objects by converting to an array in JavaScript


In JavaScript, you can loop over objects by converting them into an array of key-value pairs using various methods. Once the object is converted into an array, you can use standard array iteration methods like "for...of" loop, "forEach" method, or other array iteration techniques to access and process the key-value pairs.


Source Code

HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Tutor Joes</title>
</head>
<body>
 
	<script src="js/script.js"></script>
</body>
</html>
To download raw file Click Here

script.js
//Looping over objects by converting to an array

let user = {
  name: "Tutor Joes",
  age: 35,
  city: "Salem",
  contact: "9043017689",
};

let arr_keys=Object.keys(user);
console.table(arr_keys);

let arr_values=Object.values(user);
console.table(arr_values);

for(let i=0;i<arr_keys.length;i++)
{
  console.log(arr_keys[i]+" : "+arr_values[i]);
  //console.log(user[arr_keys[i]]);
}
To download raw file Click Here

List of Programs


JS Practical Questions & Answers


JS Practical Project