如何在javascript中创建关联数组

How to create an associative array in javascript

本文关键字:创建 关联 数组 javascript      更新时间:2023-09-26

我需要以以下格式创建一个数组:

{"3":
    {"label":"All i want for christmas",
     "song":"Alliw_1405399165.mp3",
     "name":"All i want for christmas"},
"4":
    {"label":"Call your girlfriend robyn clip",
     "song":"Gangnam_Style_2.m4a",
     "name":"Call your girlfriend robyn},
"5":
    {"label":"Gangnam style psy clip",
     "song":"Samba_De_Janeiro-world_cup_for_jivebird.m4a",
     "name":"Gangnam style psy clip"} }

我在 ajax 响应后以以下方式填充这些值:

$.each(response.result, function(i,item){
                        label = item.name;
                        if((item.special_price < item.price)&&(item.special_price!=0) && (item.special_price!=null)) {
                            label += '- is Only '+ item.special_price + item.currencysymbol;
                        }
                        tmpsongList[item.product_id].push({'label': label,
                                                    'song': item.audiofile,
                                                    'name': item.name,
                                                    'tag': item.tag,
                                                    'song_path': item.audio_url});
                });

但这会导致以下错误未捕获类型错误:无法读取未定义的属性"push"

我怎样才能创建一个这样的数组。请帮我解决这个问题感谢大家

push

数组(不是纯对象)上的一种方法,它将您传递给它的值放在数组的末尾。

您不是在尝试将值放在对象的末尾,而是尝试将其分配给特定索引。

tmpsongList[item.product_id] = { ...

它不是一个数组,它是一个映射/对象。var a = {} 是一个对象/映射。var a = [] 是一个数组。在您的情况下,您需要

tmpsongList[item.product_id] = {'label': label,
                                                'song': item.audiofile,
                                                'name': item.name,
                                                'tag': item.tag,
                                                'song_path': item.audio_url};