Search code examples
javascriptvue.jscomputed-properties

Displaying mixed arrays in computed method


I've got a computed method that allows me to display some data:

  productsSpecification() {
    var names = [];
    var numbers = [];
    this.cart.items.forEach(function(item) {
      names += "Item: " + item.product.name + " -";
      numbers += " Amount: " + item.quantity + ", ";
    });
    var together = names + numbers;
    return together;
  }

I would like to display elements in order: element from 'names' array + element from 'numbers' array: 'Item: item1 - Amount: 1'.


Solution

  • You could map it like this:

    productsSpecification() {
      return this.cart.items.map(function(item) {
        return `Item: ${item.product.name} - Amount: ${item.quantity}`; // or "Item: " + item.product.name + " - Amount: " + item.quantity;
      }).join(', ')
    }