Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript dictionary with names

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?

like image 674
Kiran Avatar asked Apr 21 '11 15:04

Kiran


People also ask

Can you make a dictionary in JavaScript?

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.

How do you check if an object is a dictionary in JavaScript?

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.


2 Answers

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 ... } 
like image 161
Lev Avatar answered Sep 18 '22 03:09

Lev


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]; 
like image 26
David Tang Avatar answered Sep 21 '22 03:09

David Tang