-1

So let's say I have an array with a bunch of values say

"abc" = 5
"bcd" = 12
"ddd" = 13

I would like to be able to loop through and print all these out in a format similar to

abc: 5
bcd: 12
ddd: 13

If there is an assoc. array that's quite large and I don't know all the keys. How do I print out all of the keys and values?

Thanks

adsfdsafdsa
  • 51
  • 1
  • 2
  • 8
  • Note: They're not generally referred to as "*associative arrays*" with JavaScript. [They should be `Object`s](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects). [`Array`s](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array), though `Object`s by inheritance, are largely associated with numeric indexes (`0` to `length - 1`). – Jonathan Lonowski Jul 11 '13 at 18:50
  • possible duplicate of [Iterating through list of keys for associative array in JSON](http://stackoverflow.com/questions/558981/iterating-through-list-of-keys-for-associative-array-in-json) – Legendre Jul 11 '13 at 19:09

1 Answers1

9

Try this:

for(var prop in obj) {
    if(obj.hasOwnProperty(prop)){
        console.log(prop + ': ' + obj[prop]);
    }
}
  • Thank you. That worked perfectly. Ah interesting.. my mentor called them associative arrays and I just went with it. – adsfdsafdsa Jul 11 '13 at 18:44
  • Well, I was not fully correct in my answer so I removed that part. Associative arrays are actually objects, as with a lot of other stuff in Javascript. How do you actually create these arrays in your code? –  Jul 11 '13 at 18:48
  • I initialize them with var myArray = new Array(); and then initialize them to stuff with myArray[name] = 5; something like that? – adsfdsafdsa Jul 11 '13 at 18:51
  • Well, I then you could call it an associative array. But it will work almost same way as an object created like this: `var a = { abc: 12 };` –  Jul 11 '13 at 18:53
  • 1
    You could look a bit more into the difference here: http://stackoverflow.com/questions/874205/what-is-the-difference-between-an-array-and-an-object –  Jul 11 '13 at 18:54