我正在尝试创建一个包含键和值列表对的字典。我能够为键值对创建一个字典,但我需要插入一个项目列表作为键值的值。 这是我的方法:
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/