This question already has answers here:
How can JavaScript arrays have non-numeric keys?
(2 answers)
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 4 months ago.
I am going crazy here, I have an associative array as seen below which is defined after the page finishes loading. However Array.forEach is returning undefined and I have no idea why. The array is most definitely populated during the loop. Can anyone give me any ideas? Also doesn't work with JQuery's $.each
Arrays are usually a mapping of index (integer from 0 to 232 − 2, inclusive) to value. In your case you've treated the array as a dictionary e.g. key (string) to value.
You've probably done something like this:
members = new Array();
members['animerox1213'] = 'Ashima';
JavaScript allows this, after all it is still an object:
typeof members === 'object'
But instead of adding a value to the array, you've actually set a non-numeric property on the object called animerox1213. That is not how an array should be used and we can observe this by checking the size:
members.length === 0;
Consequently, forEach does not do anything as it considers it an empty array.
That said, it is enumerable with for…in as it's still just an object (with enumerable properties):
for (m in members) {
console.log(m, members[m]);
}
Consider using just an object e.g. members = {} or Map. Note especially the section Objects vs. Maps.
Related
This question already has answers here:
Check if array of objects contain certain key
(6 answers)
Closed 5 months ago.
I need to find out if an array of a JS object includes an object with a specific key.
I am using,
my_array.filter((e) => Object.keys(e).includes(my_key)).length > 0
but there must be a way to do it simpler.
Any suggestions in addition to Check if array of objects contain certain key ?
Instead of .filter(…).length > 0, use .some(…).
Instead of Object.keys(…).includes(…), use … in … (or Object.hasOwn(…, …) if you need to ignore inherited properties).
So
my_array.some(e => my_key in e)
instead of filter use some, already returns true or false and it shortcircuits as soon as it finds the first
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Are Javascript arrays primitives? Strings? Objects?
(7 answers)
Closed 2 years ago.
I'm looking for an elegant way of understanding JavaScript array and objects.
I came to an anomaly in which I got stuck.
Since in PHP or other languages, when we make an array e.g
$a = [
admin => 1,
staff => 2
];
so if we want to access its element we can do so by for e.g $a[admin] and we will get 1.
similarly if its an object e.g
$a = (object) [];
$a->sadd = 'sas';
we can access it with arrow
$a->sadd
and if we try to access object elements in the style of array i.e like this $a['sadd'] it will throw error that you can not use it as array style.
But I was surprised by the anomaly in JavaScript.
I have observed that in JavaScript no matter what I am making, an array or object, the elements of both can be accessed via dot or via array style and i found no difference in there accessing style.
for e.g
var a = {sadd : 1}
I can access its element via a['sadd'] or a.sadd both will give 1
So I am confused by this anomaly and wondering whether array and object both datatypes are considered same in JavaScript?
An array is indeed an object.
Javascript is a dynamic language and accepts mixed types of entities. Also while accessing, dot notation seems to be more clearer (atleast imo) and is preferred. Bracket notation is used for dyanamic keys.
The difference between array and objects boils down to their usecase:
Array -> Contiguous block of memory
Object -> key-value pair (like a dictionary)
Your php example is actually creating what we'd call an object in JS, not an array. In JS an array is a list of items, which you can find items by array[i], or by looping.
An object is a collection of fields, which you can go into by object.fieldName or object[fieldName].
This can be confusing in JS though, because theoretically everything is an "object", including arrays, due to the way things are handled lower down..
I would recommend following along with the https://justjavascript.com/ course for good mental models on how objects work in JS.
This question already has answers here:
Why does JavaScript convert an array of one string to a string, when used as an object key? [duplicate]
(4 answers)
Why can I access object property with an array?
(2 answers)
Closed 2 years ago.
See this example:
> map = { 5: 'five' }
> map[5]
'five' // Makes sense
> arr = [5]
> map[arr]
'five' // Does not make sense
> arr = [5,6,7]
> map[arr]
undefined // I'm cool with that
So when I access an object's property with an array of length 1, it behaves as if I simply input the single element instead of the array. But when the array's length is anything but 1, it will produce the expected behavior.
What is the purpose of this behavior? To me this would simply make things harder for a developer to find a bug in their code.
If an object index is not a string or Symbol, it's converted to a string as if by its toString() method.
array.toString() performs the equivalent array.join(",").
So
map[arr]
is equivalent to
map[arr.join(",")]
If the array has one element, joining it simply returns that one element converted to a string, so it's equivalent to
map[arr[0].toString()]
and that explains your first result.
But in your second example, it returns the string "5,6,7" and there's no property with that name in the object.
This question already has answers here:
How to get all properties values of a JavaScript Object (without knowing the keys)?
(25 answers)
Closed 6 years ago.
I have a hashed object where the keys are added dynamically through user selections.
I want to iterate over it and extract the values similar to the way I would do if it was simply an array: selections.map(cart => /*do stuff*/).
How can I achieve this?
Use Object.keys()
The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
var array = Object.keys(selections).map(k => selections[k]);
// get all values from the object
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript “For …in” with Arrays
I'm trying to use the for-in syntax to loop through an array of numbers. Problem is, those numbers are getting converted to strings.
for(var element in [0]) {
document.write(typeof(element)); // outputs "string"
}
Is this standard behavior? I can think of a bunch of ways to work around it, but I'm really just looking for an explaination, to expand my understanding of JavaScript.
I think you misunderstand what JavaScript for...in does. It does not iterate over the array elements. It iterates over object properties. Objects in JavaScript are kind of like dictionaries or hashes in other languages, but keyed by strings. Arrays in particular are implemented as objects which have properties that are integers from 0 to N-1 - however, since all property names are strings, so are the indices, deep down.
Now let's take a bit different example than [0], since here index coincides with the value. Let's discuss [2] instead.
Thus, [2] is, if we ignore the stuff we inherit from Array, pretty much the same as { "0": 2 }.
for..in will iterate over property names, which will pick up the "0", not the 2.
Now, how to iterate over Arrays then, you ask? The usual way is:
var arrayLen = array.length;
for (var i = 0; i < arrayLen; i++) {
var el = array[i];
// ...
}
This is a repeat of Why is using "for...in" with array iteration a bad idea?
The for-in statement enumerates the properties of an object. In your case element is the name of the property and that is always a string.