0

I have dynamically generated array

var userData = new Array();
var userHash = "HashCode123";

// now I push object to that array:
userData[userHash].username = "Ferdo";
userData[userHash].ban = 0;

Console returning this values:

userData
[] //why this is not array of object(s)?

userData[hash]
Object {username: "Ferdo", ban: 0}

I need run userData.forEach() but I can't because array is empty? Thank you for help.

L. Dave
  • 35
  • 1
  • 7

2 Answers2

3

forEach only iterates over elements of an array. Only properties whose property name has a numeric value that is between 0 and 232-2 are considered to be elements of the array.

"HashCode123" doesn't fulfill this criteria. If you want arbitrary "key" names, you can use an object and iterate over that instead (How do I enumerate the properties of a JavaScript object?).

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

When adding string keys to an array, it's 'transforms' into an object (that's not fully accurate, but you'll get the idea with that).

An array, which is iterable, can only have numeric keys.

If you want to iterate over an object, you need to either use for let item in my_object

Here's how I like to iterate over objects though.

const keys = ['apple', 'banana', 'orange'];
let fruits = [];

keys.forEach(x => fruits[x] = `${x} is a fruit`);

// now we have fruits.apple, fruits.banana, fruits.orange
// Since it's now an object you'll need to get the keys and iterate over that

const fruit_keys = Object.keys(fruits);
fruit_keys.forEach(x => console.log(fruits[x]));

And to see it in action, here's a fiddle.

https://jsfiddle.net/scheda/4n0r5zmy/

Chris R.
  • 699
  • 8
  • 23
  • Don't you mean to make `fruits` an object instead of an array? – Felix Kling Feb 23 '16 at 16:32
  • Normally I would, yes. But in the example L. Dave posted, his was specifically an array, so that's what I used in my example. – Chris R. Feb 23 '16 at 16:33
  • But using an array gives the wrong impression. If you are not using an array as an array then you shouldn't use it. Don't repeat the mistakes the OP makes. After all, they are here to get "proper" solutions. – Felix Kling Feb 23 '16 at 16:34
  • I completely agree. Just trying to stick with what the user was originally doing to make the point of needing to use Object.keys to get string key names. – Chris R. Feb 23 '16 at 16:34