In javascript, there are many ways to create objects such as an array, object method, a new keyword, object literal, and more.
# Program to create a list of fruits properties
In this section, we will use an object literal method to create the properties lists and also iterate properties by using a fo-in loop.
Let's see, the simple instance:
➤ Example 1: program for creating a list of fruits;
In this code, we used the "object literal" method to create a list of object properties.
- <script type="text/javascript">
var fruits = {
apple: {
water : "86%",
protein : "0.3g",
fat : "34g",
sugars : "0.2g"
},
mango: {
water : "83.46g",
protein : "0.2g",
fat : "38g",
sugars : "0.16g"
}
};
/* Here, accessing the properties value */
console.log(`${Object.keys(fruits)[0]} protein is : ${fruits.apple.protein}`);
console.log(`${Object.keys(fruits)[1]} protein is : ${fruits.mango.protein}`);
- </script>
Output :
apple protein is : 0.3g
mango protein is : 0.2g
By default, all properties an object is enumerable in which means that you can iterate over them using a for-in loop in JavaScript.
Let's try to create an example:
➤ Example 2 : using for-in loop;
for(var property in fruits.apple) {
console.log(`${property}: ${fruits.apple[property]}`);
}
Output :
water: 86%
protein: 0.3g
fat: 34g
sugars: 0.2g
Comments