Reputation:
Am trying to achieve something like the following :
Key value
fruit apple,orange,banana,grapes
cooldrinks pepsi,cococola,miranda
snaks lays,kurkure
for that i use the code as:
<script>
var vars = [{key:"key", value:"val1",value:"val2",value:"val3",value:"val4"}];
vars[0].key = "fruit";
vars[0].val1 = "apple";
vars[0].val2 = "orange";
vars[0].val3 = "banana";
vars[0].val4 = "grapes";
</script>
But it is not possible for large dictionaries how can i implement such dictionaries with huge content? can anyone suggest me a simplest method?
In the case of dynamic array what should i need to change in my code?
Upvotes: 0
Views: 107
Reputation: 2573
You should first of all create this key/values object:
function Pairs() {
this.key= "",
this.values= new Array()
}
this object will hold your key and values for all the things.
Next up you need to create a dictionary array to hold all the Pairs:
var dictionary = new Array();
then, create your objects, fill them up with data and add them to dictionary:
var fruit = new Pairs();
fruit.key = "fruit";
fruit.values[0] = "banana";
fruit.values[1] = "Orange";
fruit.values[2] = "Apple";
dictionary.push(fruit); //adding fruit to dictionary
var car = new Pairs();
car.key = "car";
car.values[0] = "Honda";
car.values[1] = "Toyota";
car.values[2] = "Ferrari";
dictionary.push(car); //adding car to dicitonary
once dictionary is populated, you can access the objects like:
dictionary.length; //get the length of all the objects present in dictionary
dictionary[0].key; //get the key of a particular object
Upvotes: 0
Reputation: 6170
You can use js objects to do this
var dictionary = [
{ fruit: ['apple', 'orange', 'banana', 'grapes'] },
{ cooldrinks: ['pepsi', 'cocacola', 'miranda'] },
{ snacks: ['lays', 'kurkure'] }
];
You can then access them like this
dictionary.fruit; // returns apple, orange, banana, grapes
dictionary.snacks[0]; // returns lays
You can even use []
notation
dictionary["fruit"][0];// returns apple
Upvotes: 0
Reputation: 94101
How about:
var data = [
{fruit: ['apple','orange','banana','grapes']},
{cooldrinks: ['pepsi','cocacola','miranda']},
{snacks: ['lays','kurkure']}
]
Upvotes: 1
Reputation: 64923
Why you use an array for this? Use an object instead:
var dictionary = {
key1: ["value1", "value2"],
key2: ["value3", "value4"]
};
If you want to obtain all keys, you may use Object.keys
:
var allKeys = Object.keys(dictionary);
Also, you can access a key using dot syntax or indexed syntax:
var key1value = dictionary.key1;
key1value = dictionary["key1"];
Upvotes: 0