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. As I am new to JS, having trouble finding the clean way. Can some pls suggest?
Thanks
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:
... which simplifies access:
Alternatively:
And access with:
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:
Then you could easily iterate through all your "columns" with a for loop:
Edit>> Good news, here is now an easier, native and more efficient way of emulating a dict in JS: Also exploit that JS is weakly typed. Rather type inference. Anyway..
Here's how (an excerpt from Google Chrome's console):
Are you trying to use a JSON object?
To access:
I suggest not using an array unless you have multiple objects to consider. There isn't anything wrong this statement.
Here's a dictionary that will take any type of Key as long as the toString() property returns unique values. The dictionary uses anything as the value for the key value pair.
See http://www.codeproject.com/Articles/684815/Would-JavaScript-Benefit-from-a-Dictionary-Object
To use the dictionary as is:
Dictionary Code Below: