Search code examples
javascriptarraysangularjsdictionaryangularjs-scope

“.push is not a function” error while inserting key-value to an array in AngularJS


I’m trying push ItemId(as a key) and PartNO(value) to an array dynamically based on Noof ItemPartDtls using a for loop so that I can again fetch those PartNOs using ItemID in the for loop when required.

But I got the error message:

TypeError: NoofParts.push is not a function

while pushing.

var NoofParts = []; // initialized globally

if ($scope.ItemPartDtls.length > 0) {    
    for (let e = 0; e <= $scope.ItemPartDtls.length - 1; e++) {
        // NoofParts.push({ "ItemID": $scope.ItemsInfo[d].ITEM_ID, "PartNO":  $scope.ItemPartDtls[e].PART_NO });
        NoofParts.push({ ItemID: $scope.ItemsInfo[d].ITEM_ID, PartNO: $scope.ItemPartDtls[e].PART_NO});
        // error here: TypeError: NoofParts.push is not a function
    }
}

...

function GetPartdtls(ItmId){
    for(i = 0; i < NoofParts.length; i++){
        if(NoofParts[i].ItemID == ItmId) {
            console.log("ItemID:- " + NoofParts[i].ItemID + " PartNO:- "  + NoofParts[i].PartNO);
        }
    }
}

Solution

  • Try like this way

     var NoofParts =  []; // initialized globally
    
    if ($scope.ItemPartDtls.length > 0) {    
       for (let e = 0; e <= $scope.ItemPartDtls.length - 1; e++) {
           // NoofParts.push({ "ItemID": $scope.ItemsInfo    [d].ITEM_ID, "PartNO":  $scope.ItemPartDtls[e].PART_NO});
            let newArr = { 
                           ItemID: $scope.ItemsInfo[e].ITEM_ID, //here your typo error
                           PartNO: $scope.ItemPartDtls[e].PART_NO
                          }
            NoofParts.push(newArr);
        }
    }