0

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!

3
  • 2
    might be a typo, but you are missing a closing ']' in your sample code: $("[name='" + prop + "']").text = obj[prop]; Commented Feb 16, 2015 at 17:11
  • 1
    I'm wondering if you really need var obj = JSON.parse(data);. Commented Feb 16, 2015 at 17:13
  • 1
    you are working with array of objects Commented Feb 16, 2015 at 17:15

1 Answer 1

2

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');
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.