Carson
Carson

Reputation: 1189

JSON object properties display as "0" in javascript

I have some server side methods returning a JSON object that my JS parses and tries to enumerate through the properties to set the input with the same name as the property value. My application is in ASP.Net MVC 5 and I got the JSON working correctly.

Here is my JS:

function ProcessPropertyChange(url, name)
{
   var val = $("[name='" + name + "'").val();
   url = url + "&propValue=" + val;

    $.get(url, function (data) {
        var obj = JSON.parse(data);
        for (var prop in obj)
        {
            if(obj.hasOwnProperty(prop))
            {
                $("[name='" + prop + "'").text = obj[prop];
                alert(prop);
            }
        }
    });
}

An example JSON string would be:

[{"FullAddress" : "123 w. oak", "ParentName":""}]

That was taken from my code.

When I view my object in the developer's console I can see the properties with the proper names, FullAddress and ParentName, however when I try to enumerate through them it returns "0" and the value of obj[prop] is always [Object object].

Any ideas? Can post more code if you need.

Thanks!

Upvotes: 0

Views: 409

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

obj is an array which has an object as its member, so the object has indexes 0...length-1 that is why you are getting 0.

If you are expecting the array to have only 1 value, then instead of returning an array return the object, else in your js code read the object from the 0th index of the data. Also you can use $.each() like

$.get(url, function (data) {
    //since data is an array
    var obj = data[0];
    $.each(obj, function (value, prop) {
        $("[name='" + prop + "'").text = value;
        alert(prop);
    })
}, 'json');

Upvotes: 2

Related Questions