简体   繁体   中英

How to create and add values to a JavaScript Dictionary

I'm trying to create a Dictionary with a key and a value list pair. I'm able to create a dictionary for a key value pair but I need to insert a list of Items as value for a key value. Here is my approach:

keys = ['A', 'B', 'C'];
Elements Corresponding to 'A' : 'apple'
Elements Corresponding to 'B' : 'ball', 'balloon','bear'
Elements Corresponding to 'C' : 'cat','cow'

and my result should be like:

{ key:'A' value:['apple'], key:'B' value:['ball',balloon','bear'], Key:C' value:['cat','cow']}

Here is just a sample data, I will get data dynamically from a table.Please help me out.Thanks In advance.

使用Json

var xObj = {'A' : ['apple'] ,'B' : ['ball','balloon','bear'],'Ç' : ['cat','cow'] };

This code can add a new key-value pair into some dictonary like object.

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;
}

Here's an example:

/* 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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM