javascript - 如何为 JavaScript 字典创建和添加值

标签 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' 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;
}

关于javascript - 如何为 JavaScript 字典创建和添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20883113/

相关文章:

JavaScript 调试问答 : How do I `console.log()` Map?

javascript - 如何在 Piwik 中跟踪 javascript 事件?

javascript - CircleCi 有时无法在构建中连接到 Postgres

javascript - jquery .unload() 仅在 iframe 中访问的第一个页面触发

Javascript 用标签 bbcode 换行文本?

javascript - 使用包含方法名称的变量调用方法

jquery - Summernote富文本编辑器: minHeight and maxHeight options have no effect

javascript - 从动态生成的标签调用ajax并从ajax获取值

c# - 使用枚举和 |作为字典键

python - 如何修复此 Python TypeError : iteration over non-sequence?