2

Here is a snippet of javascript from my C# web MVC application:

$.ajax({
         url: 'myurl'
        }).done(function(response) {
          $scope.Vdata = JSON.parse(response);
          return $scope.$apply();
        });

The JSON response form this call looks like this

"{
    \"renditions\": {
        \"live\": \"true\",
        \" type\": \"default\",
        \"rendition\": {
            \"name\": \"Live \",
            \"url\": \"http: //mysite\"
        }
    }
}"

I would like to wrap the json response rendition object into an array to look like this-(note the added square brackets for the array)

"{
    \"renditions\": {
        \"live\": \"true\",
        \" type\": \"default\",
        \"rendition\": [{
            \"name\": \"Live \",
            \"url\": \"http: //mysite\"
        }]
    }
}"

I tried something like this which didn’t work:

$.ajax({
    url: 'myurl'
}).done(function(response) {
    var tmp;
    if (!respose.renditons.rendition.isArray) {
        tmp = respose.renditions.renditon;
        respose.renditon = [];
        respose.renditon.push(tmp);
    }
    $scope.Vdata = JSON.parse(response);
    return $scope.$apply();
});

The response will sometimes include the rendition object as an array so I only need to convert to an array in cases where its not.

Can someone please help me with the correct javascript to convert the json object into an array. Preferably modifying my existing code

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
Milligran
  • 3,031
  • 9
  • 44
  • 56

3 Answers3

0

You can check if the object is an array using this:

Object.prototype.toString.call( response.renditions.rendition ) === '[object Array]'

And you can simplify the conversion to an array -- just wrap it as an array using x = [x]:

if (Object.prototype.toString.call( response.renditions.rendition ) !== '[object Array]') {
    response.renditions.rendition = [response.renditions.rendition];
}

Fiddle demo.

Community
  • 1
  • 1
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
0

Try this:

$.ajax({
    url: 'myurl'
}).done(function(response) {
    var json = JSON.parse(response);
    if(!Array.isArray(json.renditions.rendition)) {
        json.renditions.rendition = [json.renditions.rendition];
    }
    return json;
});

Fiddle demo (kind of...)

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
-1

add data type JSON to your ajax post. example

$.ajax({type: "POST",
        url: URL, 
        data: PARAMS,
        success: function(data){
            //json is changed to array because of datatype JSON
                alert(data.renditions);
            },            
        beforeSend: function (XMLHttpRequest) { 
            /* do something or leave empty */
        },
            complete: function (XMLHttpRequest, textStatus) { /*do something or leave empty */ },  
        dataType: "json"}
       );
srakl
  • 2,565
  • 2
  • 21
  • 32