如何在JavaScript中创建键/值对列表

时间:2016-07-29 13:27:24

标签: javascript

我有一个数组内的股票清单。 每个股票属于一个部门,例如

CBB , VZ belongs to Communications Sector 
UPS , RRTS belongs to Transportation Sector 
AAC belongs to Health  Sector 

当我循环遍历数组时,输出是

CBB
VZ
UPS
RRTS
AAC 

我需要以这种方式显示

CBB  Communications
VZ   Communications
UPS  Transportation
RRTS Transportation
AAC   Health

我的代码

$(document).ready(function() {
   var list_of_stocks= [
    "CBB",
    "VZ",
    "UPS",
    "RRTS",
    "AAC "
]

for(var i=0;i<list_of_stocks.length;i++)
{
console.log(list_of_stocks[i]);
}

});

http://jsfiddle.net/n3fmw1mw/202/使用上面的代码

如何维护另一个键值对列表结构以有效实现此目的

(我不想修改数组list_of_stocks), 所以想要创建另一个键值对列表。 感谢您阅读本文

2 个答案:

答案 0 :(得分:3)

您可以使用javascript对象:

var list_of_stocks= {
  "CBB": "Communications",
  "VZ": "Communications",
  "UPS": "Transportation",
  "RRTS": "Transportation",
  "AAC": "Heath"
};
for (var key in list_of_stocks) {
  if (list_of_stocks.hasOwnProperty(key)) {
    console.log(key + " -> " + list_of_stocks[key]);
  }
}

请参阅http://jsfiddle.net/n3fmw1mw/204/

答案 1 :(得分:0)

为什么不使用对象来执行此操作?

obj = {
     communications: ['CBB', 'VZ'],
     transportation: ['UPS', 'RRTS'],
     health: ['AAC']
}

或和多维数组

newArr = [['CBB', 'VZ'],['UPS', 'RRTS'],['AAC']]

然后你知道newArr [0]将拥有Communications数组,依此类推。