0

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.

2

1 Answer 1

2

Square bracket notation:

var parentLevel = 0;

function renderCategoryList (receivedCategories) {
    ...
    category["parentName" + parentLevel] = receivedCategories[z].Name;
    parentLevel++;
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This did the trick! I will accept your answer when possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.