0

I have an MVC5 project that uses this jQuery AJAX call

    $.ajax({
        url: "/ClientDetails2/" + document.getElementById('clientid').value,
        type: "GET",
        dataType: "json"
    })
    .done(function (json) {
        $('#FirstName').text(json['Client'].FirstName);

        $.each(json['Cases'],         <-----
            function(value) {         <-----
                console.log(value);   <-----
            });                       <-----
    });

to return this JSON:

{
    Client: {
        Id: 1,
        LastName: "Clark",
        FirstName: "Keith",
        PrimaryPhone: "(555) 555-1212",
        Email: "[email protected]"
    },
    Cases: [
        "Case1",
        "Case2",
        "Case3"
    ]
}

The $('#FirstName').text(json['Client'].FirstName); works fine and updates the DOM correctly.

Where I am getting hung up is in iterating thru Cases.

What am I missing here?

Thanks, Keith Clark

3
  • check this demo Commented Jul 9, 2016 at 2:36
  • Thanks for that, but I need to be able to iterate using the .each option as I will never know how many items are in that array Commented Jul 9, 2016 at 2:39
  • check this updated demo Commented Jul 9, 2016 at 2:42

2 Answers 2

1

$.each() takes two parameters index and value

var json  = {
    Client: {
        Id: 1,
        LastName: "Clark",
        FirstName: "Keith",
        PrimaryPhone: "(555) 555-1212",
        Email: "[email protected]"
    },
    Cases: [
        "Case1",
        "Case2",
        "Case3"
    ]
};
         
 $.each(json['Cases'], function(index, value) {        
       console.log(index +' -> '+value);  
});     
                             
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that reply...I had the epiphany as you were typing your reply
0

Figured out my issue. Even though there is no actual key:value paring in the array, there is still an implied index that has to be accounted for in the function call. I modified my code to this:

    $.each(json['Cases'],         
        function(index,value) {         
            console.log(value);   
        });  

and all works as expected now.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.