Home > Back-end >  Accessing a property of the last object in an array in computed vue
Accessing a property of the last object in an array in computed vue

Time:06-16

I have an empty products array and users can add new products if they want. My goal is I want to save the last productKey and save it in a Vuex state.

//data
products: []

//method
addNewProduct() {
      this.products.push({
        productKey: '',
        productName: ''
      })
},

I want to get the key of the last added product (last object). I've tried this way

lastKey() {
  return this.products[this.products.length-1].productKey
}

This doesn't work as it says cannot read properties of undefined (reading 'productKey'). Any help would be greatly appreciated. thank you.

CodePudding user response:

All state-related (including computed properties) run before hook created .Because products is initially empty so you try to access productKey of last item will result cannot read properties of undefined (reading 'productKey'). You can use optional chaining to check possibility exists.

lastKey() {
  return this.products[this.products.length-1]?.productKey
}

CodePudding user response:

I think your code is already correct. this happened because products array is empty

  • Related