Skip to content Skip to sidebar Skip to footer

Javascript Array.foreach With Custom Keys Not Working

I have dynamically generated array var userData = new Array(); var userHash = 'HashCode123'; // now I push object to that array: userData[userHash].username = 'Ferdo'; userData[us

Solution 1:

forEach only iterates over elements of an array. Only properties whose property name has a numeric value that is between 0 and 2-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?).

Solution 2:

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 thatconst 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/

Post a Comment for "Javascript Array.foreach With Custom Keys Not Working"