我正在尝试使用键和值列表对创建一个Dictionary。我能够为键值对创建一个字典,但我需要插入一个Items列表作为键值的值。 这是我的方法:
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']}
这里只是一个示例数据,我将从表中动态获取数据。请帮助我。谢谢提前。
答案 0 :(得分:2)
使用Json,
var xObj = {'A' : ['apple'] ,'B' : ['ball','balloon','bear'],'Ç' : ['cat','cow'] };
答案 1 :(得分:2)
此代码可以将新的键值对添加到某些类似dictonary的对象中。
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;
}
答案 2 :(得分:1)
以下是一个例子:
/* 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]);
}