-2

Given an javascript object:

myList = {
  "1": "Winter",
  "2": "Spring",
  "3": "Summer",
  "4": "Fall"
}

and supposing that the variable season contains the first item, how do I access "1" and/or "Winter"?

Edit: myList['1'] is not the answer I am looking for because I want to access either "1" or "Winter" from the season variable. It is not a duplicate of the marked question.

Instead, I want to do something like:

for(var season in myList) {
   foo( season.key ); // should be "1" on the first pass
   bar( sesson.val ); // should be "Winter" on the first pass
}

I've seen somewhere that you can do an inner loop to get the key and value. Is there some other way aside from doing that?

howellmartinez
  • 1,195
  • 1
  • 13
  • 24

2 Answers2

1

Libraries like lodash and underscore were made to help with these kinds of problems. You can use the lodash#forEach function to iterate over the values (and keys if applicable) in a collection (array or object).

Check out: https://lodash.com/docs#forEach

So with your example you could do something like:

_.forEach(myList, function(value, key) {
  foo(key); // 1
  bar(value); // "Winter"
});
0

You can simply get the value of the key by:

myList['1']

To get the key from the value there is no standard method available in javascript. You would have to write your own method for this.

Bioaim
  • 928
  • 1
  • 13
  • 26