Question

I have a series of ajax json responses that I need to convert to a common type of array. The issue is that each json response is slightly different.

Here are two examples of responses I might receive:

var contacts = [{ "ContactId" : "1", "ContactName" : "Bob" },{ "ContactId" : "2", "ContactName" : "Ted" }];
var sites = [{ "SiteId" : "1", "Location" : "MN" },{ "SiteId" : "2", "Location" : "FL" }];

I'm trying to write a method that converts either collection to a common type. An example of the above responses converted would look like this:

var convertedContacts = [{ "value" : "1", "text" : "Bob" },{ "value" : "2", "text" : "Ted" }];
var convertedSites = [{ "value" : "1", "text" : "MN" },{ "value" : "2", "text" : "FL" }];

So I'm trying to use the map function of jquery to facilitate this requirement. Although I can't seem to figure out how to dynamically query for the different property values that will exist depending on which json collection I'm passing into the function.

Here is an example of what I'm trying to do:

function ConvertResponse(arrayToConvert, text, value)
{
    var a = $.map(arrayToConvert, function(m) { 
        return "{ \"text\" : "+eval("m."+text)+", \"value\" : "+eval("m."+value)+" }"
    });
}

I also tried this:

function ConvertResponse(arrayToConvert, text, value)
{
    var a = $.map(arrayToConvert, function(m) { 
        return "{ \"text\" : " + m.$(text) + ", \"value\" : " + m.$(value) + " }";
    });
}

And this is how you would call it:

var convertedContacts = ConvertResponse(contacts, "ContactName", "ContactId");
var convertedSites = ConvertResponse(contacts, "Location", "SiteId");

Unfortunately this does not seem to work in the least.

Was it helpful?

Solution

Like this?

var contacts = [{ "ContactId" : "1", "ContactName" : "Bob" },{ "ContactId" : "2", "ContactName" : "Ted" }];
var sites = [{ "SiteId" : "1", "Location" : "MN" },{ "SiteId" : "2", "Location" : "FL" }];

function convertResponse(response, text, value) {
  return $.map(response, function(it) {
    return {
      value: it[value],
      text: it[text]
    };
  });
}

var convertedContacts = convertResponse(contacts, 'ContactId', 'ContactName');
var convertedSites = convertResponse(sites, 'SiteId', 'Location');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top