Reputation: 1199
I have the following function:
function renderCategoryList (receivedCategories) {
var allCategories = [];
for (var i in receivedCategories) {
var category = {}
category.categoryName = receivedCategories[i].Name;
category.categoryId = receivedCategories[i].Id;
category.categoryParentCategoryId = receivedCategories[i].ParentCategoryId;
if (receivedCategories[i].ParentCategoryId != null) {
var parentLevel = 0;
var parentId = receivedCategories[i].ParentCategoryId;
for (var z = 0; receivedCategories.length > z; z++) {
var parentName = "parentName" + parentLevel;
if (receivedCategories[z].Id == parentId) {
category.parentName = receivedCategories[z].Name; // the "category.parentName" should be dynamic. At first run this should be category.parentName0.
parentId = receivedCategories[z].ParentCategoryId
var parentExists = true;
parentLevel++; //if a parentId exists this should raise the level with +1 and therefore at the next run the name should be "category.parentName1".
z = 0;
}
}
}
allCategories.push(category);
}
return allCategories;
}
I am trying to create a dynamic name for the variable parentName
in category
. At first run through the for loop the name of this variable should be parentName0
- second run it should be parentName1
and so on until the receivedCategories[i].ParentCategoryId
is null
.
The method shown above ignores the var parentName = "parentName" + parentLevel;
and therefore in each run of the loop the category.parentName
is overridden.
How can I make the parentName
variable in category
dynamic?
I hope I have explained this in an understandable way. Otherwise please let me know so I can try to elaborate.
Upvotes: 0
Views: 49
Reputation: 136074
Square bracket notation:
var parentLevel = 0;
function renderCategoryList (receivedCategories) {
...
category["parentName" + parentLevel] = receivedCategories[z].Name;
parentLevel++;
...
}
Upvotes: 2