akrama81
akrama81

Reputation: 351

How to create a dictionary of list in javascript

I have a table as follows which I'm getting from a mysql database:

Col2   | Col3                   | Col4
1      | Name1(something_1234)  | Some_date
1      | Name1(something_3456)  | Some_date
2      | Name3(something_7890)  | Some_date
2      | Name4(something_0988)  | Some_date

And I'm getting this data into html using javascript as follows:

<script>
            var new_col2 = [], new_col3 =[];
            {% for b in obj %}
            new_col2.push("{{b.col2 }}");
            new_col3.push("{{b.col3 }}");
            {% endfor %}
            console.log(new_col2);
            console.log(new_col3);
    </script>

Is it possible to create a dictionary as follows using javascript using the above for loop:

{'1': ['Name1(something_1234)', 'Name1(something_3456)'], '2': 'Name3(something_7890)', 'Name4(something_0988)']}

Upvotes: 0

Views: 6084

Answers (2)

Munzer
Munzer

Reputation: 2318

Assuming that obj is javascript list of object we can loop through the list, and push each row into the map we will create, if you don't know map, check this

something like this.

var myMap= new Map();
obj.forEach(function(element) {
   // my map set (key , value )
    myMap.set(element.col2,element.col3);
});

you can access the value of key 1 myMap.get(1);, this will return the value mapped with key 1.

Upvotes: 0

huydq5000
huydq5000

Reputation: 284

You can do something like this:

<script>
            var dictionary = {}
            {% for b in obj %}
                if (!dictionary["{{b.col2 }}"]) {
                    dictionary["{{b.col2 }}"] = [];
                }
                dictionary["{{b.col2 }}"].push({{b.col3 }});
            {% endfor %}
            console.log(dictionary);            
</script>

Upvotes: 1

Related Questions