使用数组作为键值对中的值创建字典:java Script

时间:2014-09-10 05:50:08

标签: javascript

我试图实现以下目标:

  Key                      value

fruit               apple,orange,banana,grapes
cooldrinks          pepsi,cococola,miranda
snaks               lays,kurkure

为此我使用代码:

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

但是对于大词典来说,我怎么能用大量内容来实现这样的词典呢?谁能建议我一个最简单的方法?

在动态数组的情况下,我需要在代码中更改哪些内容?

4 个答案:

答案 0 :(得分:1)

怎么样:

var data = [
  {fruit: ['apple','orange','banana','grapes']},
  {cooldrinks: ['pepsi','cocacola','miranda']},
  {snacks: ['lays','kurkure']}
]

答案 1 :(得分:0)

为什么要为此使用数组?改为使用对象

var dictionary = {
   key1: ["value1", "value2"],
   key2: ["value3", "value4"]
};

如果您想获得所有密钥,可以使用Object.keys

var allKeys = Object.keys(dictionary);

此外,您可以使用点语法索引语法访问密钥:

var key1value = dictionary.key1;
key1value = dictionary["key1"];

答案 2 :(得分:0)

您可以使用js对象执行此操作

var dictionary = [
  { fruit: ['apple', 'orange', 'banana', 'grapes'] },
  { cooldrinks: ['pepsi', 'cocacola', 'miranda'] },
  { snacks: ['lays', 'kurkure'] }
];

然后您可以像这样访问它们

dictionary.fruit;     // returns apple, orange, banana, grapes
dictionary.snacks[0]; // returns lays

您甚至可以使用[]表示法

dictionary["fruit"][0];// returns apple

答案 3 :(得分:0)

首先应创建此键/值对象:

function Pairs() {
    this.key= "",
    this.values= new Array()
}

此对象将保存所有内容的键和值。

接下来你需要创建一个字典数组来保存所有的对:

var dictionary = new Array();

然后,创建对象,用数据填充它们并将它们添加到字典中:

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

填充字典后,您可以访问以下对象:

dictionary.length; //get the length of all the objects present in dictionary
dictionary[0].key; //get the key of a particular object

<强> See the DEMO here