I need to create a dynamic array with a loop.. but I cant seem to get the desired results.
the array I want is:
{
"CategoryName": "somecategoryname",
"Date": "02-17-2012",
"Id": 24,
"ProductToHide": [
{
"IsHide": true,
"ProductId": "someid"
}
],
"ProductsToAdd": [
{
"MealSequence": "S1",
"ProductId": "Someid"
},
{
"MealSequence": "S2",
"ProductId": "Snack_11"
}
],
"UserId": "1"
}
and I am using the following function to add products:
addProduct: function(id){
var tempArr = [];
$.each(this.mCData.ChildCategories, function(i, item){
$.each(item.PList, function(j, jsonPr){
if (jsonPr.TID == id){
addProduct = new mealTypeProduct();
addProduct.data = jsonPr;
tempArr = addProduct.modifyProduct();
}
})
})
// queryStr = {"add" : tempArr};
// this.modificationArray.push(queryStr);
this.modificationArray['add'].push(tempArr);
console.log(this.modificationArray);
}
Its giving me the following error:
this.modificationArray.add.push is not a function
this.modificationArray['add'].push(tempArr);
the initializing is done in the following manner:
var mealType = {
chosenDate: new Date(), tabViewHtml: '',
modificationArray: [], saveArray: [],
}
What am I doing wrong?
This line:
replaces
tempArrwith a new value, so at the end of the$.eachcall it will have the value from the last matching product (which may not be an array) rather than being an array of all of them. If that is what you want then that’s not a problem.As to the actual error you quote: what type of thing is
this.modificationArray? Does it have a member calledadd? Does that member have apush()function? Is it initialized properly, or is it left uninitialized? If the latter, then there’s your problem: you need to initialize it before you can callpush().UPDATE: If
this.modificationArrayis initialized as[], as in the new sample code, then it is an array itself; it does not have anaddmember. The code should saythis.modificationArray.push(tempArr).Alternatively, if you really do want an
addmember, thenthis.modificationArrayshould be initialized asmodificationArray : {add:[]}