1

I'm wondering how I can access each object in this json string via jquery.

The string returned looks like:

{"Appointments":["\/Date(1507238100000)\/"],"Sessions":[]}

I need access to both the Appointments object as well as the Sessions object, I can't seem to figure it out.

I tried to access the Appointments object by index like:

$.each(data, function (index, element) {
                        $.each(data, function (index, element) {
                            //alert(JSON.stringify(element, null, 4));
                            alert(element.Appointments[index]);
                        });
                        //value = new Date(parseInt(element.Appointments.substr(6)));
                        //var rowContent = "<tr><td>" + value + "</td></tr>";
                        //$('#appointmentsTable tbody').append(rowContent);
                    });

This does not work however, thoughts?

2 Answers 2

2

You don't have to access element by element.Appointments[index] when you are looping though an array by $.each.

For example

var data = {"Appointments":["\/Date(1507238100000)\/"],"Sessions":[]};

To loop though object in data.Appointments, you simply do this

$.each(data.Appointments, function(index, element){
    console.log(element);
});

To loop though object in data.Sessions, you simply do this

$.each(data.Sessions, function(index, element){
    console.log(element);
});

For more example about $.each, please refer to JQuery API Documentation here.

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

1 Comment

Ah jeez, I dunno. Major brain fart! Thanks for your help.
2

You don't actually need jquery for this at all.

You could use plain javascript. If your project uses ES6, you could write it as:

// extract appointments and sessions from data
let { Appointments, Sessions } = data

// iterate over appointments
Appointments.forEach((appointment, index) => { console.log(appointment) })

// iterate over sessions
Sessions.forEach((session, index) => { console.log(session) })

Basically you don't really need index inside your iteration callback - you can directly access the elements you are iterating over instead. The same would apply to your jquery function as well.

If you prefer to use jQuery, your code could be rewritten as:

$.each(data.Appointments, (index, elem) => alert(elem))

1 Comment

Interesting, I did not think to do it that way. Thank you for the response.

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.