简体   繁体   中英

“.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 PartNO s 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);
        }
    }
}

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);
    }
}

Your code should ideally work, but to double proof, try the below method

(function() {

  let NoofParts = []; // initialized globally

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

})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM