0

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)']}

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.