简体   繁体   中英

How to Create a list of key/value pairs in JavaScript

I have got a list of stocks inside a array . Each Stock belongs to a Sector , For example

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

When i am looping through the array , the output is

CBB
VZ
UPS
RRTS
AAC 

I am in requirement to display it this way

CBB  Communications
VZ   Communications
UPS  Transportation
RRTS Transportation
AAC   Health

My Code

$(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/ with the above code

How to maintain a another key value pair list structure to achieve this efficiently

(I don't want the array list_of_stocks to be modified) , so want to create another key value pair list . Thank you for reading this

You can use javascript object:

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

See http://jsfiddle.net/n3fmw1mw/204/

Why don't you use an object to do this?

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

or and multidimensional array

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

then you know that newArr[0] will have the Communications array and so on.

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