-4

I'm using an array.find below and it works to return BreakdownPalletID when the itemScan value is found in the array. If it's not found my application returns a 'Cannot read property breakdownPalletID of undefined'. The user enters the itemScan so I want to have this behavoir and then to signify to the user that that string was not found. How can I handle this undefined error?

 let palletID = this.transferPalletBreakdownData.Sku.find(x => x.sku == this.itemScan).breakdownPalletID
      console.log(palletID);
Joe Starnes
  • 471
  • 1
  • 6
  • 20
  • Why not check if the value returned from `find()` is `undefined` before trying to access the property? – Shidersz May 31 '19 at 03:22
  • 2
    Possible duplicate of [JS: Handle with find() property undefined](https://stackoverflow.com/questions/52389757/js-handle-with-find-property-undefined) – adiga May 31 '19 at 03:22
  • `(this.transfer.Sku.find(x => x.sku == this.itemScan) || {}).breakdownPalletID` – adiga May 31 '19 at 03:24

3 Answers3

2

Array.prototype.find() method will return null if an item does not exist else it will return the expected item. So just add null checks it's enough to get rid of the error.

 const itemFound = this.transferPalletBreakdownData.Sku.find(x => x.sku == this.itemScan)


let palletID = itemFound && itemFound.breakdownPalletID
console.log(palletID);

You want more than one item based on criteria matched then we need to used filter instead of a find().

const matches = this.transferPalletBreakdownData.Sku.filter(x => x.sku == this.itemScan)

const items = matches.map(item => itemFound.breakdownPalletID)

console.log(items)
Raja Jaganathan
  • 33,099
  • 4
  • 30
  • 33
  • awesome this looks to have worked... do you know how to have the find function return multiple results if it finds multiple matches? – Joe Starnes May 31 '19 at 03:49
  • Array.prototype.find() will return only one item(first match), I guess you are expecting filter(), can you please try with filter function. – Raja Jaganathan May 31 '19 at 03:51
  • I was able to filter the array just to the items I wanted to see... this seems to be working great..... I'm using this so the user can filter an array to only see items he 'searches' for.... once I accomplish this how can I 'unfilter' the array if the user selects something along the lines of a 'clear filters' button and then show the entire array again? – Joe Starnes May 31 '19 at 14:53
1

Use a logical OR operator ||:

let palletID = (this.transferPalletBreakdownData.Sku.find(x => x.sku == this.itemScan) || {}).breakdownPalletID;
console.log(palletID);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

Try out the following code.

const sku = this.transferPalletBreakdownData.Sku.find(x => x.sku == this.itemScan);
if (sku) {
  console.log(sku.breakdownPalletID);
} else {
  console.log('No SKU');
}
Julian W.
  • 1,501
  • 7
  • 20