Evochrome Evochrome - 3 months ago 11
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).

Array

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

"1"
and let's say the second has value
"4"
. 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?):

array[someIndex].children.forEach(
//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
cat1
and
cat2
without knowing it has
index 2
(this could also be
6
or
42
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
cat1
,
cat2
from the second level subarray with, in this case,
index 2
)

Thanks in advance, any help is appreciated!

Evoc

Answer

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]) {
       console.log(arr[0][i][j]['msg']);
   }
}