2
votes

I have this code that populates an observableArray. It loops through an array named modules, and pushes each item on the observableArray one by one. Now every item on the modules array has an array inside it named submodules. I am trying to make this submodules into an observableArray.

I've isolated the code that doesn't work below. I always have a console error of "Uncaught TypeError: Cannot read property 'length' of undefined" from jQuery. Also, I've tried ko.observableArray(moduleValue.submodules) to return an observableArray for submodules and it works, but I need to be able to make the construct below work, if possible.

// Loop through items.
$.each(arr, function(key, value) {

    // Loop through modules.
    $.each(value, function(moduleIndex, moduleValue) {
        self.modules.push({
            name: moduleValue.name,

            //
            // Can't make this work
            // Shouldn't this return an observableArray?
            //
            submodules: function() {
                var result = ko.observableArray();

                // Loop through submodules.
                $.each(moduleValue.submodules, function(submoduleIndex, submoduleValue) {
                    result.push(submoduleValue.name);
                });
                return result;
            }()

        });
    });
});

EDIT

As requested, the value or arr:

{
    "modules" : [
        { 
            "name" : "Companies",
            "submodules" : [
                { "name" : "All Companies" },
                { "name" : "All Active" },
                { "name" : "All Inactive" }
            ] 
        }, 
        { "name" : "Settings" }
    ]
}
1
How does arr look like? Provide at least one item for example - haim770
@haim770: I've edited the question to include the value of arr. - g_b
@haim770: You are correct. I missed that part. Thank you for spending some time on this question. Please make it in an answer form so I can accept it as the correct answer. Thanks! - g_b

1 Answers

1
votes

The problem is that you don't make sure that submodules property actually exists on the iterated object before trying to call $.each on it.

Try this:

if (moduleValue.submodules && moduleValue.submodules.length) {
    $.each(moduleValue.submodules, function(submoduleIndex, submoduleValue) {
        result.push(submoduleValue.name);
    });
}

Also, have you considered using the ko.mapping plugin instead?