Link to home
Start Free TrialLog in
Avatar of ITNC
ITNCFlag for United States of America

asked on

Jquery for each loop of arrays inside an array

I have a function that returns an array that will contain an unknown number of associative arrays and I need help iterating through those arrays to get the key and values.

Here is an example array:

[{"name":"test","value":"1234"},{"name":"test2","value":"5678"}] 

Open in new window


I need to use Jquery to iterate through each array of those arrays and alert the values (I will use them later but for now alerting is fine).
I took a crack at it and this is what I have so far in my first attempt:

For my tests the variable data is set to that array above.

EDIT: I just found that the array in the data variable is actually a string. So I suppose I will need to convert to an array somehow. I have been trying to do this, I will post if I come up with anything.

$.each(data, function( key, value ) {
                $.each(key, function( k, v ) {
                    alert( "Key: " + k + ", Value: " + v );
                });
            });

Open in new window


I get this error using the code above:
Uncaught TypeError: Cannot use 'in' operator to search for '68' in [{"name":"test","value":"1234"},{"name":"test2","value":"5678"}]
ASKER CERTIFIED SOLUTION
Avatar of Rainer Jeschor
Rainer Jeschor
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ITNC

ASKER

I actually managed to get it working but since you provided a working example I will go ahead and accept yours as the answer. I forgot that I could set the data type on my ajax POST to JSON and have it process it itself. Then I used the following code to get the data (I went ahead and added the rest of the code I was planning on using in place of alerts):

$.each(data, function( key, value ) {
                var obj = jQuery.parseJSON(value);
                $('#tags' + uuid + '').tagsinput('add', { "uuid": obj.value , "tagName": obj.name});
            });

Open in new window