Evochrome Evochrome - 1 year ago 72
Javascript Question

How to get all children of a subArray in Javascript

So here's my problem:

So this is what my array looks like, I have shown a fragment of it here (from the console window).


It's overall pretty basic right? Except for it's indexing. As you see the first has value

and let's say the second has value
. As for it's subarrays, these have custom indexes too.

Therefore, the old fashioned:

for(i=0; i<array.length; i++){
someVar = array[i];
//do something

won't work.

I get the 1 or 4 from iterating through another array, so don't need to get those.

I want to get all subArrays(not the further nested subArrays, only the second level).

So basicly what I want is something like this(is there something like this?):

//do something with **this**

To make it more practical for you:
So I know that the first array has
index 1
. How can I get the values of
without knowing it has
index 2
(this could also be
for example). In this case, the first array only has one subArray but I would like to make it work for multiple subArrays. (to clarify, select
from the second level subarray with, in this case,
index 2

Thanks in advance, any help is appreciated!


Answer Source

Those aren't arrays. You have

[   {   "1": { etc...

which is an array containing an object containing multiple other objects. You can't really use a for(i=...) loop for this, because your keys aren't sequential. You should use a for ... in loop instead:

arr = [{"1":{....}}];

for (i in arr[0]) {
   for (j in arr[0][i]) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download