简体   繁体   English

如何在JavaScript中创建列表字典

[英]How to create a dictionary of list in javascript

I have a table as follows which I'm getting from a mysql database: 我有一张从MySQL数据库中获取的表格,如下所示:

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: 而且我正在使用javascript将此数据导入html中,如下所示:

<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: 是否可以使用上述for循环使用javascript创建如下字典:

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

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>

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 假设obj是对象的javascript列表,我们可以遍历该列表,并将每一行推入我们将要创建的地图中,如果您不知道地图,请选中

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); 您可以访问键1 myMap.get(1); , this will return the value mapped with key 1. ,这将返回键1映射的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM