javascript loop through array and object properties
To loop through an array in javascript, you can use for loop which the syntax is almost the same as in other languages such as java, c++, php, etc. There is also the forEach function that comes with array objects. The regular for loop is friendly to programmers coming from other languages that has the similar syntax for for loop. forEach is less code, more javascrpt-ish way of looping through arrays.
var fruits = ['Apple', 'Banana', 'Cherry', 'Orange', 'Pear']; for(var i=0; i<fruits.length; i++) { console.log(fruits[i]); } fruits.forEach(function (fruit) { console.log(fruit); }); // Both of them prints // Apple // Banana // Cherry // Orange // Pear
To loop through object properties in javascript, you can use the for…in loop and Object.keys() plus forEach. The for…in loop will loop through all the object keys including those inherited from the prototype, so you need to use hasOwnProperty to make sure you are only working on the keys belong to the object itself. The Object.keys() method returns an array of a given object’s own enumerable properties, in the same order as that provided by a for…in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). Once you got the array of keys, you can then use the forEach function to loop through each property in the object.
var favoriteFruit = { "Amy": { "fruit": "Apple" }, "Ben": { "fruit": "Banana" }, "Carol": { "fruit": "Cherry" }, "Olivia": { "fruit": "Orange" }, "Pualine": { "fruit": "Pear" } }; for (var key in favoriteFruit) { if (favoriteFruit.hasOwnProperty(key)) { console.log(key + "'s favorite fruit is " + favoriteFruit[key]['fruit']); } } Object.keys(favoriteFruit).forEach(function (key) { console.log(key + "'s favorite fruit is " + favoriteFruit[key]['fruit']); }); // Amy's favorite fruit is Apple // Ben's favorite fruit is Banana // Carol's favorite fruit is Cherry // Olivia's favorite fruit is Orange // Pualine's favorite fruit is Pear
Search within Codexpedia
Search the entire web