Well, is it possible in javascript to create a list of objects in javascript?. The concept of lists is not there in Javascript. To create an effect of lists, we can use arrays and maps.
Table of Contents:
Create a List of Objects in Javascript using Array
In the below example, we will be creating a list of objects using arrays as lists do not exist in javascript.
Example:-
Create a list of objects with properties voterName, eligibility, and city
Code:-
let customList = [ { voterName: 'Paul', eligibility: 'Yes' , city: "NewYork"}, { voterName: 'Eva', eligibility: 'No', city: "Santiago"}, { voterName: 'Veronica', eligibility: 'Yes' , city: "NewYork"} ]; for (let i = 0; i < customList .length; i ++ ){ console.log(customList[i]); }
Output:-
Frequently Asked:
{ voterName: 'Paul', eligibility: 'Yes', city: 'NewYork' } { voterName: 'Eva', eligibility: 'No', city: 'Santiago' } { voterName: 'Veronica', eligibility: 'Yes', city: 'NewYork' }
Explanation:-
Here, in the above code, we create an array of objects named customList and then iterate the array using a for-loop to get the items sequentially.
Create a Dynamic List of Objects in Javascript
We can create an effect of dynamic list creation in javascript using arrays.
Example:-
Create a dynamic list of objects with properties voterName, eligibility and city
Code:-
let customList = []; let voterNames = ["Paul", "Eva", "Veronica"]; let eligibility = ["Yes", "No", "Yes"]; for(i = 0; i< voterNames.length; i++ ) { var objectValue1 = {}; objectValue1['type1'] = 'voterName'; objectValue1['value1'] = voterNames[i]; objectValue1['type2'] = 'eligibility'; objectValue1['value2'] = eligibility[i]; customList.push(objectValue1); } for (let i = 0; i < customList .length; i ++ ) { console.log(customList[i].type1 + " : " + customList[i].value1 + " , " + customList[i].type2 + " : " + customList[i].value2 ); }
Output:-
voterName : Paul , eligibility : Yes voterName : Eva , eligibility : No voterName : Veronica , eligibility : Yes
Explanation:-
- Here, in the above code, we create an array of objects named customList. In the customList we add properties ‘voterName,’ and ‘eligibility’, and their corresponding values using a for-loop.Â
- To sequentially get the values of customList, we are using for-loop and printing on console the property and its corresponding value.
Example:-
Create a dynamic list of names
Code:-
let customList = new Array(); customList.push('George'); customList.push('Ryan'); for (var i = 0; i < customList.length; i ++ ){ console.log(customList[i]); }
Output:-
George Ryan
Explanation:-
Here, in the above code, we create an array named customList and push the values to it using the push() method. Again, we are iterating the values of customList sequentially using for-loop.Â
I hope this article helped you create a list of objects in javascript using arrays. Good Luck !!!