Brian J Brian J - 3 months ago 18
Ajax Question

How to convert a JSON object to Javascript array filtered by key?

I'm returning a JSON object from an Ajax request which outputs the following keys and values:

[{"App_Name":"Maccy D's","ID":2017},{"App_Name":"B King","ID":2011}]


What I need to do is convert this object to a Javascript array where each App_Name and ID value is concatenated as one string in the array. So for example
['Maccy D's 2017', 'B King 2011']
etc...

What I have tried is calling a
var assetsArray= JSON.parse(assetJSON);
but when I bind the assetsArray to a list it shows
[object Object]
for each menu item. Instead of the intended App_Name + ID concatenation:

enter image description here

Question:

How can you convert a JSON object to Javascript array filtered by key?

This is how I bind the JSON returned to the menu list:

Ajax request:

//call an Ajax GET for the asset name data
$.ajax({
url: asset_list_request_url,
cache: false,
success: function(assetJSON){
bindAssetNamesMenu(assetJSON);
}
});


Mapping function:

function bindAssetNamesMenu(assetJSON)
{

var assetsArray = JSON.parse(assetJSON);

$.each(assetsArray, function(i)
{
var li = $('<li/>')
.addClass('ui-menu-item')
.attr('role', 'menuitem')
.appendTo(assetMenu);


var a = $('<a>')
.addClass('ui-all')
.appendTo(li);

var input = $('<input/>')
.addClass('ui-all')
.attr('type', 'checkbox')
.appendTo(a);


var span = $('<span>')
.text(assetsArray[i])
.appendTo(a);


});

}

Answer
  1. you don't need var assetsArray = JSON.parse(assetJSON);
  2. keep your names straight, not assetJSON and assetArray
  3. you have to access the property of the array index, like assetJSON[i].App_Name

Then your code is working fine!

var data = [{
  "App_Name": "Maccy D's",
  "ID": 2017
}, {
  "App_Name": "B King",
  "ID": 2011
}];

var assetMenu = $("ul");
bindAssetNamesMenu(data);

function bindAssetNamesMenu(assetJSON) {
  $.each(assetJSON, function(i) {
    var li = $('<li/>')
      .addClass('ui-menu-item')
      .attr('role', 'menuitem')
      .appendTo(assetMenu);

    var a = $('<a>')
      .addClass('ui-all')
      .appendTo(li);

    var input = $('<input/>')
      .addClass('ui-all')
      .attr('type', 'checkbox')
      .appendTo(a);

    var span = $('<span>')
      .text(assetJSON[i].ID + " - " + assetJSON[i].App_Name)
      .appendTo(a);
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>