I want to create a dictionary in JavaScript like the following:
myMappings = [ { "Name": 10%}, { "Phone": 10%}, { "Address": 50%}, { "Zip": 10%}, { "Comments": 20%} ]
I want to populate an HTML table later and want to set the titles of table to the first column of myMappings and the width of columns to the second. Is there a clean way to do it?
Actually there is no 'dictionary' type in JavaScript but we can create key-value pairs by using JavaScript Objects. Create a new JavaScript Object which will act as dictionary. Syntax: Key can be a string , integer. If you just write key1 or any number, it will treat as a string.
The simplest approach to check if something is a dictionary in Javascript in a way that will not also return true when given an array is: if (a. constructor == Object) { // code here... } This was inspired by the answer here.
Another approach would be to have an array of objects, with each individual object holding the properties of a column. This slightly changes the structure of "myMappings", but makes it easy to work with:
var myMappings = [ { title: "Name", width: "10%" }, { title: "Phone", width: "10%" }, { title: "Address", width: "50%" }, { title: "Zip", width: "10%" }, { title: "Comments", width: "20%" } ];
Then you could easily iterate through all your "columns" with a for loop:
for (var i = 0; i < myMappings.length; i += 1) { // myMappings[i].title ... // myMappings[i].width ... }
The main problem I see with what you have is that it's difficult to loop through, for populating a table.
Simply use an array of arrays:
var myMappings = [ ["Name", "10%"], // Note the quotes around "10%" ["Phone", "10%"], // etc.. ];
... which simplifies access:
myMappings[0][0]; // column name myMappings[0][1]; // column width
Alternatively:
var myMappings = { names: ["Name", "Phone", etc...], widths: ["10%", "10%", etc...] };
And access with:
myMappings.names[0]; myMappings.widths[0];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With