0

I have List of Object as a response from server in javascript. How i can access object members or how i can loop through the object using jquery.?

This is my current script.

main.addDrodownOptionsforRoom = function (selector, data)
        {
            var dropdown = $(selector);
            if (dropdown !== null)
            {
                dropdown.html("");
                dropdown.append($('<option></option>').val("").html("Select..."));
                dropdown.append($('<option></option>').val("All").html("All"));
                $.each(data, function (index, val)
                {
                    dropdown.append($('<option></option>').val(val).html(index)); 
                });
                $(selector).removeAttr("disabled");
            }
        };

In "data" i can see the List of objects. Can any body tell me how to access the members in it.

PaRsH
  • 1,320
  • 4
  • 28
  • 56
  • http://stackoverflow.com/questions/3830099/asp-net-mvc-html-dropdownlist-populated-by-ajax-call-to-controller – AliRıza Adıyahşi Mar 05 '13 at 12:26
  • 2
    What have you tried? Seriously there are 1000 question about how to access javascript object and iterate over them: See [here](http://stackoverflow.com/questions/4846041/javascript-object-iterating-over-properties), [here](http://stackoverflow.com/questions/4923938/how-to-iterate-over-this-object), [here](http://stackoverflow.com/questions/1897553/jquery-iterate-over-object-with-each), [here](http://stackoverflow.com/questions/2203958/jquery-recursive-iteration-over-objects) or [here](http://stackoverflow.com/questions/9354834/iterate-over-object-literal-values) just to name a few. – Christoph Mar 05 '13 at 12:27
  • What type is `val`? String, Number, Object? – Beetroot-Beetroot Mar 05 '13 at 12:33

1 Answers1

0

Try this

main.addDrodownOptionsforRoom = function (selector, data)
{
    var dropdown = $(selector);
    if (dropdown !== null)
    {
        dropdown.html("");
        var html = '';
        html += '<option value="">Select...</option>';
        html += '<option value="ALL">All</option>';
        dropdown.append(html);

        var options = '';
        $.each(data, function (key, val)
        {
            options += '<option value="'+key+'">'+val+'</option>';
        });
        dropdown.append(options);

        $(selector).removeAttr("disabled");
    }
};

But since I don't know how your object is build up, I can't give you the exact solution. if something like this:

obj = [name:'a name',number:'555'];

you could do something like:

alert(obj.name); // displays 'a name'
alert(obj.number); // displays '555'
Brainfeeder
  • 2,604
  • 2
  • 19
  • 37