So for each checkbox selected, I am getting the associated id and depending on values there deducing the node values, which is working fine. The problem I am facing is creating a proper javascript object with values from all checkboxes.
Here's the function,
function finlizeJParams()
{
var jsonOutput=[];
var array = $("input[type='checkbox']:checked").map(function(){
var str=this.id;
var data=[];
var objID=str.substring(str.lastIndexOf("c_")+2,str.lastIndexOf("_n_"));
var objName=str.substring(str.lastIndexOf("_n_")+3,str.lastIndexOf("_p_"));
var objParentID=str.substring(str.lastIndexOf("_p_")+3,str.lastIndexOf("_pn_"));
var objParentName=str.substring(str.lastIndexOf("_pn_")+4);
data['ItemID']=objID;
data['ItemName']=objName;
data['ItemParentID']=objParentID;
data['ItemParentName']=objParentName;
jsonOutput.push(data)
return jsonOutput;
}).get()
JSON.stringify(array);
}
This seems to be working as I am getting arrays when I try to print it on console, See below
0: Array[0]
ItemParentName: "Fruit"
ItemParentID: "7"
ItemID: "8"
ItemName: "Apple"
1: Array[0]
ItemParentName: "Fruit"
ItemParentID: "7"
ItemID: "9"
ItemName: "Orange"
However, if I do a JSON.stringify(jsonOutput), I get empty arrays [[],[]]? What am I doing wrong? Also, how can I group these array by parentID/Name and then convert to a JSON object?
1 Answer 1
You are treating an array as a plain object.
While arrays inherit from objects, they are designed for numerical indexed, sequential data and only properties with numerical values will be included when you pass them through JSON.stringify.
If you want to use named keys, then use an object ({}), not an array ([]).
var data={};
.map()(transform one array to another), but not actually returning anything from the callback, so it's the same as if you did.each(loop over an array with no explicit result); and I've no idea what that.get()is doing on the end there.jsonOutputis global to all iterations of the array, and you're adding to it on each loop; so you'll add 1 item the 1st time around, 2 on the 2nd, 3 on the 3rd, etc. Either use.eachand keepjsonOutputas your accumulator (drop thevar array =) or use.mapand just returndataeach time (drop all references tojsonOutput).cats = { 'cat1': [item1, item2], 'cat2': [item3, item4] }will work; if you need the categories to be in order, it needs to be more likecats = [ { 'name': 'cat1', 'items': [item1, item2], 'name': 'cat2', 'items': [item3, item4] } ]. Try adding to some structures by hand before putting the code into the loop.