I hard coded the following array and I can use it to insert selections into an Autocomplete dropdown. It seems to be an array of JSON objects, though I am a JS novice and could be wrong. It works.
var boroughData = [
{"label":"New York, Bronx, Bronx County, New York, United States","value":"Bronx, Bronx County, New York, United States"},
{"label":"New York, Staten Island, Richmond County, New York, United States","value":"Staten Island, Richmond County, New York, United States"}
];
I want to provide similar data from a database and assemble it via a .map() function. I have something working, but the output is a different format/type. It seems to be an array with one long string, though again, I could be wrong. An example (with different cities) is below. Note the initial and ending ” that is not in my hard coded array above.
["{"label":"Dallas, Cockr... Texas, United States"}", "{"label":"Dallas, Downt... Texas, United States"}", "{"label":"Dallas, East ... Texas, United States"}"]
The data from the database currently looks like the following, though it could be changed, if that helps.
{"label":"Dallas, Cockrell Hill, Dallas County, Texas, United States", "value":"Dallas, Cockrell Hill, Dallas County, Texas, United States"}
I tried string manipulation to replace/remove the initial and ending ” but I could not get it to work. Maybe I need something different in the .map() function to create objects. My .map() in an ajax success option is as follows
success: function (data){
boroughData = $.map( data, function (item){
return item.boroughString;
//returning {"label":"Dallas, Cockrell Hill, Dallas County, Texas, United States", "value":"Dallas, Cockrell Hill, Dallas County, Texas, United States"}
});
alert(jQuery.isArray(boroughData) + "|bD1"); //true, is array
return boroughData;
}
How do I get a return result that is the same type/format as my hard coded array? Please be specific with code. I don’t follow general instructions well.
Since the data that you get in
item.boroughStringis a string, you probably can parse it withJSON.parse(or usejson2.jsfor browsers who don’t support this functionality – see also this question : Parse JSON in JavaScript?) and it should convert you this string in a full JSON object.