Search code examples
javascriptarraysangularjsfirebug

Why array of objects is showing blank in firebug though it contain items - Javascript + AngularJS


Following is the screenshot, I am unable to trace what is going wrong here with JavaScript.

If you see that the array in firebug is showing a blank array and if I console the length it is also coming 0. BUT if I click the (+) icon its showing the data. Let me know what I am doing wrong with the code.

Code -

            //scope.days is an array of objects
            var newArr = [];
            var myArr = [];
            myArr = scope.days;
            console.log(myArr.length);
            var weekNum = 1;
            newArr['week'+weekNum] = [];
            for(var i=1; i<= myArr.length; i++) {
                newArr['week'+weekNum].push(myArr[i]);
                if(i%7 == 0){
                    weekNum = weekNum + 1;
                    newArr['week'+weekNum] = [];
                }
            }
            scope.days = newArr;

Firebug Screenshot -

Image


Solution

  • It's helpful to understand that objects can be accessed using either bracket or dot notation. Also note that Arrays are also objects.

    So myObj with a property myProp can be accessed using either myObj["myProp"] or myObj.myProp. Square bracket notation is useful when we want to dynamically access a property but we don't know it's identifier at design time. i.e. we want to use a dynamically created label:

    var label = "myProp";
    myObj[label] = "xyz";
    

    So the point of the above is that square bracket notation is a means to reference properties of an object. In your code you do this:

    newArr['week'+weekNum] = [];
    

    apparently with the intent of using 'week'+weekNum as an index into the array, but instead what it is actually doing is making a property assignment. So you can continue to make 'week'+weekNum all week long and array length will still be zero because you are not assigning elements to the array but instead generating new properties.

    What you likely want is just

    newArr[weekNum] = [];