rajeev rajeev - 3 months ago 17
jQuery Question

using dataFilter from jquery .ajax with json data

how can i produce a modified vaild JSON data string from the JSON data coming from the ajax call. it is necessary to do this with dataFilter.

retData (data returned) from ajax call is:

{"8":"vacation","7":"birthday","5":"summer","4":"2013","3":"2014","6":"winter","2":"2015","1":"2016"}


JS code:

'dataFilter': function (retData, json) {
console.log('retData='+retData);
data = [];
$.map(retData, function (value,key) {
console.log('indx=i'+key+', value='+value);
node = {
'id' : 'i'+key,
'text' : value,
'icon' : '/',
'data' : value, //'metadata' : value,
'state' : {'opened' : false},
'children' : true
}
data.push( node );
});
console.log('final-data='+data);
return data;
//return JSON.stringify(data);
}


but instead i am getting error in browser console: it seems $.map is having the issue when run in 'dataFilter', it runs fine in 'success' call (but plugin strictly wants processing to be done in 'dataFilter')

TypeError: invalid 'in' operand a
https://www.localhost.com/jscript/jquery/jquery-2.2.0.min.js
Line 2

Answer

The dataFilter's arguments are both strings per the docs. You need to convert retData to an object before you can call $.map on it:

  'dataFilter': function(retData, json) {
    data = [];
    $.map(JSON.parse(retData), function(value, key) {
      console.log('indx=i' + key + ', value=' + value);
      node = {
        'id': 'i' + key,
        'text': value,
        'icon': '/',
        'data': value, //'metadata' :  value,
        'state': {
          'opened': false
        },
        'children': true
      }
      data.push(node);
    });
    console.log('final-data=' + JSON.stringify(data));
    return data;
    //return JSON.stringify(data);
  },

Fiddle

Comments