如何创建JavaScript字典并向其添加值

如何创建JavaScript字典并向其添加值,javascript,jquery,dictionary,Javascript,Jquery,Dictionary,我正在尝试创建一个包含键和值列表对的字典。我可以为键值对创建字典,但我需要插入一个项目列表作为键值的值。 我的做法如下: keys = ['A', 'B', 'C']; Elements Corresponding to 'A' : 'apple' Elements Corresponding to 'B' : 'ball', 'balloon','bear' Elements Corresponding to 'C' : 'cat','cow' 我的结果应该是: { key:'A' valu

我正在尝试创建一个包含键和值列表对的字典。我可以为键值对创建字典,但我需要插入一个项目列表作为键值的值。 我的做法如下:

keys = ['A', 'B', 'C'];
Elements Corresponding to 'A' : 'apple'
Elements Corresponding to 'B' : 'ball', 'balloon','bear'
Elements Corresponding to 'C' : 'cat','cow'
我的结果应该是:

{ key:'A' value:['apple'], key:'B' value:['ball',balloon','bear'], Key:C' value:['cat','cow']}
这里只是一个示例数据,我将从表中动态获取数据。请帮助我。提前感谢。

使用


这段代码可以将一个新的键值对添加到一些类似于命令的对象中

var dictionary= {};
function insertIntoDic(key, value) {
 // If key is not initialized or some bad structure
 if (!dictionary[key] || !(dictionary[key] instanceof Array)) {
    dictionary[key] = [];
 }
 // All arguments, exept first push as valuses to the dictonary
 dictionary[key] = dictionary[key].concat(Array.prototype.slice.call(arguments, 1));
 return dictionary;
}
下面是一个例子:

/* Define dictionary */
var dict = {};

/* Define keys */
var keys = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

/* Assign array as value for each key */
for (var n = 0; n < keys.length; n++) {
    dict[keys[n]] = [];
}

/* Make up a bunch of words */
var words = ["apple", "ball", "balloon", "bear", "cat", "cow"];

/* Append these words to the dictionary according to their first letter */
for (n = 0; n < words.length; n++) {
    dict[words[n][0].toUpperCase()].push(words[n]);
}
/*定义字典*/
var dict={};
/*定义关键点*/
var keys=“abcdefghijklmnopqrstuvxyz”;
/*将数组指定为每个键的值*/
对于(var n=0;n
我不太明白,你似乎已经回答了你的问题。只需使用一个数组作为每个键的值,并将项附加到数组中。。。我只会得到一个动态数据。我甚至不知道有多少元素属于某个键值。我得到的只是动态数据。。我甚至不知道列表中有多少元素。我将获得JSON格式的数据,如{data:[{'key':'a',value:'apple'},{'key':'b',value:{'ball'},{'key':'b',value:'balloon'}我也尝试过同样的方法,但我只得到了键,而不是列表项。我在代码中出错,因此它不会附加项,只创建键。我更新代码-当前版本按预期工作。对不起,我尝试了您的解决方案,但对我无效。我制作了一个JSFIDLE供您参考。看一看,您错过了搜索条件数组,我交换了工作代码的循环在这里,但如果您尝试在real app中使用它,请不要忘记添加代码以排除重复记录(如有必要)。这里我将正确获取列表中的对象..如何访问该列表中的值。。。
/* Define dictionary */
var dict = {};

/* Define keys */
var keys = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

/* Assign array as value for each key */
for (var n = 0; n < keys.length; n++) {
    dict[keys[n]] = [];
}

/* Make up a bunch of words */
var words = ["apple", "ball", "balloon", "bear", "cat", "cow"];

/* Append these words to the dictionary according to their first letter */
for (n = 0; n < words.length; n++) {
    dict[words[n][0].toUpperCase()].push(words[n]);
}