[javascript] Javascript foreach loop on associative array object

Why my for for-each loop is not iterating over my JavaScript associative array object?

// defining an array
var array = [];

// assigning values to corresponding keys
array["Main"] = "Main page";
array["Guide"] = "Guide page";
array["Articles"] = "Articles page";
array["Forum"] = "Forum board";

// expected: loop over every item,
// yet it logs only "last" assigned value - "Forum"
for (var i = 0; i < array.length; i++) {
    console.log(array[i]);
}

EDIT: jQuery each() could be helpful: https://api.jquery.com/jQuery.each/

This question is related to javascript arrays foreach

The answer is


_x000D_
_x000D_
var obj = {_x000D_
  no: ["no", 32],_x000D_
  nt: ["no", 32],_x000D_
  nf: ["no", 32, 90]_x000D_
};_x000D_
_x000D_
count = -1; // which must be static value_x000D_
for (i in obj) {_x000D_
  count++;_x000D_
  if (obj.hasOwnProperty(i)) {_x000D_
    console.log(obj[i][count])_x000D_
  };_x000D_
};
_x000D_
_x000D_
_x000D_

in this code i used brackets method for call values in array because it contained array , however briefly the idea which a variable i has a key of property and with a loop called both values of associate array

perfect Method , if you interested, press like


arr_jq_TabContents[key] sees the array as an 0-index form.


You can Do this

var array = [];

// assigning values to corresponding keys
array[0] = "Main page";
array[1] = "Guide page";
array[2] = "Articles page";
array[3] = "Forum board";


array.forEach(value => {
    console.log(value)
})

There are some straightforward examples already, but I notice from how you've worded your question that you probably come from a PHP background, and you're expecting JavaScript to work the same way -- it does not. A PHP array is very different from a JavaScript Array.

In PHP, an associative array can do most of what a numerically-indexed array can (the array_* functions work, you can count() it, etc.) You simply create an array and start assigning to string-indexes instead of numeric.

In JavaScript, everything is an object (except for primitives: string, numeric, boolean), and arrays are a certain implementation that lets you have numeric indexes. Anything pushed to an array will effect its length, and can be iterated over using Array methods (map, forEach, reduce, filter, find, etc.) However, because everything is an object, you're always free to simply assign properties, because that's something you do to any object. Square-bracket notation is simply another way to access a property, so in your case:

array['Main'] = 'Main Page';

is actually equivalent to:

array.Main = 'Main Page';

From your description, my guess is that you want an 'associative array', but for JavaScript, this is a simple case of using an object as a hashmap. Also, I know it's an example, but avoid non-meaningful names that only describe the variable type (e.g. array), and name based on what it should contain (e.g. pages). Simple objects don't have many good direct ways to iterate, so often we'll turn then into arrays first using Object methods (Object.keys in this case -- there's also entries and values being added to some browsers right now) which we can loop.

// assigning values to corresponding keys
const pages = {
  Main: 'Main page',
  Guide: 'Guide page',
  Articles: 'Articles page',
  Forum: 'Forum board',
};

Object.keys(pages).forEach((page) => console.log(page));

Here is a simple way to use an associative array as a generic Object type:

_x000D_
_x000D_
Object.prototype.forEach = function(cb){_x000D_
   if(this instanceof Array) return this.forEach(cb);_x000D_
   let self = this;_x000D_
   Object.getOwnPropertyNames(this).forEach(_x000D_
      (k)=>{ cb.call(self, self[k], k); }_x000D_
   );_x000D_
};_x000D_
_x000D_
Object({a:1,b:2,c:3}).forEach((value, key)=>{ _x000D_
    console.log(`key/value pair: ${key}/${value}`);_x000D_
});
_x000D_
_x000D_
_x000D_


This is (essentially) incorrect in most cases:

var array = [];
array["Main"] = "Main page";

That creates a non-element property on the array with the name Main. Although arrays are objects, normally you don't want to create non-element properties on them.

If you want to index into array by those names, typically you'd use a Map or a plain object, not an array.

With a Map (ES2015+), which I'll call map because I'm creative:

let map = new Map();
map.set("Main", "Main page");

you then iterate it using the iterators from its values, keys, or entries methods, for instance:

for (const value of map.values()) {
    // Here, `value` will be `"Main page"`, etc.
}

Using a plain object, which I'll creatively call obj:

let obj = Object.create(null); // Creates an object with no prototype
obj.Main = "Main page"; // Or: `obj["Main"] = "Main page";`

you'd then iterate its contents using Object.keys, Object.values, or Object.entries, for instance:

for (const value of Object.values(proches_X)) {
    // Here, `value` will be `"Main page"`, etc.
}

This is very simple approach. The Advantage is you can get keys as well:

for (var key in array) {
    var value = array[key];
    console.log(key, value);
}

For ES6:

array.forEach(value => {
  console.log(value)
})  

For ES6: (If you want value, index and the array itself)

array.forEach((value, index, self) => {
  console.log(value, index, self)
})  

If the node.js or browser supported Object.entries(), it can be used as an alternative to using Object.keys() (https://stackoverflow.com/a/18804596/225291).

_x000D_
_x000D_
const h = {_x000D_
  a: 1,_x000D_
  b: 2_x000D_
};_x000D_
_x000D_
Object.entries(h).forEach(([key, value]) => console.log(value));_x000D_
// logs 1, 2
_x000D_
_x000D_
_x000D_

in this example, forEach uses Destructuring assignment of an array.