Combining properties of JavaScript objects into one

Just starting my Vue journey and encountering a slight challenge.

Displayed below is a table with various items:

Whenever an item is selected and its quantity increased, I need my addOptional method (optional) to update a variable with the item's quantity concatenated with its code. For example, if I select a hammer, it should look like this `

let variable = optional.Qty + 'x' + optional.Code

If I were to console.log the result, it would appear as 2x1

Now, if I choose another option, let's say Saw, I would need to append the new choice to the existing variable separated by a Pipe ( | ). For example, it should look like this.

2x1 | 1x2

How can I achieve this? Would using an array be the best approach?

Here's what I have so far:

new Vue({
  el: '#app',
  data() {
    return {
      Optionals: [
        { Code: 1, Name: 'Hammer', Value: 50.00, Qty: 0 },
        { Code: 2, Name: 'Saw', Value: 50.00, Qty: 0 },
        { Code: 3, Name: 'Nail', Value: 60.00, Qty: 0 }
      ]
    }
  },
  methods: {
    addOptional(optional) {
      // The variable below should receive the value of the quantity plus the code. If more than one option is chosen the variable must receive this new value and separate with pipe example Qty (2) x Code (2) | Qty (3) x Code (2)
      optional.Qty += 1;

      let Code = [optional.Qty + 'x' + optional.Code];
    },

    remove(optional) {

    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <template>
    <div class="user-list">
      <table>
        <thead>
          <tr>
            <th>#Code</th>
            <th>Name</th>
            <th>Unit Value</th>
            <th>Total Value</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="optional in Optionals" :key="optional.Code">
            <td>
              <button @click="optional.Qty ? optional.Qty-- : false">-</button>
              <input type="text" :value="optional.Qty">
              <button @click="addOptional(optional)">+</button>
            </td>
            <td>{{ optional.Name }}</td>
            <td>{{ optional.Value }}</td>
            <td>{{ optional.Value * optional.Qty }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </template>
</div>

Answer №1

This situation appears to be an ideal scenario for utilizing a computed property:

computed: {
  Code: function () {
    return this.Opcionais
      .filter( opcional => opcional.Qtd > 0 )
      .map( opcional => opcional.Qtd + 'x' + opcional.Code )
      .join( ' | ' );
  }
}

Take a look at this complete example below, where you can see the code in action beneath the table and observe it updating in real-time:

new Vue({
  el: '#app',
  data() {
    return {
      Opcionais: [
        { Code: 1, Nome: 'Martelo', Valor: 50.00, Qtd: 0 },
        { Code: 2, Nome: 'Serrote', Valor: 50.00, Qtd: 0 },
        { Code: 3, Nome: 'Prego', Valor: 60.00, Qtd: 0 }
      ]
    }
  },
  computed: {
    Code: function () {
      return this.Opcionais
        .filter( opcional => opcional.Qtd > 0 )
        .map( opcional => opcional.Qtd + 'x' + opcional.Code )
        .join( ' | ' );
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <template>
    <div class="usuario-lista">
      <table>
        <thead>
          <tr>
            <th>#Code</th>
            <th>Nome</th>
            <th>Valor Unitário</th>
            <th>Valor Total</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="opcional in Opcionais" :key="opcional.Code">
            <td>
              <button @click="opcional.Qtd > 0 && opcional.Qtd--">-</button>
              <input type="text" v-model.number="opcional.Qtd">
              <button @click="opcional.Qtd++">+</button>
            </td>
            <td>{{ opcional.Nome }}</td>
            <td>{{ opcional.Valor }}</td>
            <td>{{ opcional.Valor * opcional.Qtd }}</td>
          </tr>
        </tbody>
      </table>
    </div>
    <p>Code: {{Code}}</p>
  </template>
</div>

Answer №2

Although I don't have much experience with Vue, you can utilize the reduce method to work with Opcionais like this:

const Opcionais = [
  { Code: 1, Nome: 'Martelo', Valor: 50.00, Qtd: 0 },
  { Code: 2, Nome: 'Serrote', Valor: 50.00, Qtd: 0 },
  { Code: 3, Nome: 'Prego', Valor: 60.00, Qtd: 0 }
];

const result = Opcionais.reduce((arr, { Qtd, Code }) => {
  return [...arr, `${Qtd}x${Code}`];
}, []).join(' | ');

console.log(result);

Answer №3

Utilizing the spread operator is a great way to maintain the current state while adding new items. You can also employ the 'reducer' to join with pipes, or simply handle it in the HTML, as you prefer.

new Vue({
  el: '#app',
  data() {
    return {
      Optional: [
        { Code: 1, Name: 'Hammer', Value: 50.00, Qty: 0 },
        { Code: 2, Name: 'Saw', Value: 50.00, Qty: 0 },
        { Code: 3, Name: 'Nail', Value: 60.00, Qty: 0 }
      ],
      Elements: []
    }
  },
  methods: {
    addOptional(optional) {
      // The variable below should receive the value of the quantity plus the code. If more than one option is chosen the variable must receive this new value and separate with pipe example Qty (2) x Code (2) | Qty (3) x Code (2)
      optional.Qty += 1

      this.Elements = [...this.Elements, (optional.Qty + 1) + 'x' + optional.Code]
      },

    remove(optional) {

    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <template>
    <div class="user-list">
      <table>
        <thead>
          <tr>
            <th>#Code</th>
            <th>Name</th>
            <th>Unit Value</th>
            <th>Total Value</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="optional in Optional" :key="optional.Code">
            <td>
              <button @click="optional.Qty ? optional.Qty-- : false">-</button>
              <input type="text" :value="optional.Qty">
              <button @click="addOptional(optional)">+</button>
            </td>
            <td>{{ optional.Name }}</td>
            <td>{{ optional.Value }}</td>
            <td>{{ optional.Value * optional.Qty }}</td>
          </tr>
        </tbody>
      </table>
      <pre>{{ Elements.join("|") }}</pre>
    </div>
  </template>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determine the number of stored values in a specific key by utilizing stringify within localstorage

Is there a way to determine the number of unique values stored under one key in local storage? For instance: Here is the content of my local storage: [{"id":"item-1","icon":"google.com"},{"id":"item-2","icon":"youtube.com"}] In this case, I would like ...

CSS modified after opening a modal dialog that has loaded external HTML content

Within my ASP.NET MVC project, I am utilizing a tab wizard. On one of the tabs, I trigger a modal dialog by loading HTML content from an external API. However, once I close the wizard and navigate to the next tab, the table style (specifically border color ...

Implementing jquery-confirm in CodeIgniter: A Step-by-Step Guide

I'm having some trouble with the jquery-confirm plugin from . Everything seems to be working fine, but when I try to delete an item, the jquery pops up an alert. However, when I click "okay", it doesn't actually delete the item. I can't figu ...

Run a JavaScript function in 5 seconds

I'm looking to execute this function after a 5-second delay: $(document).ready(function() { $("#signInButton").trigger('click'); }); Your assistance is greatly appreciated. ...

What is the best way to manage the browser tab close event specifically in Angular, without it affecting a refresh?

I am trying to delete user cookies when the browser tab is closed. Is this achievable? Can I capture the browser tab close event without affecting refreshing? If I attempt to use beforeunload or unload events, the function gets triggered when the user ref ...

Potential causes for Chrome to send duplicate requests

In my nginx server logs, I have the following entries (IPs and paths altered for illustration purposes): 101.101.101.101 - - [15/Apr/2020:14:46:03 +0000] "GET /item/download-file/ready/5e971e290107e HTTP/2.0" 200 142940 "https://example.com/referer" "Mo ...

In Vue 3, there exist numerous modules that are distinguished solely by variations in their letter casing

I've been working on a Vue 3 application where I'm utilizing SVG code as a background URL in SASS. $bg-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 14 11'><path fill='# ...

When the Next.js app is built, the API route provides the initial data, which typically occurs during development

I am encountering an issue with my Next.js page using App Router. The page retrieves data from its route API, which is obtained from MQTT. During development (running dev), when we send a request to api/getLocation, it returns updated data from MQTT. Howev ...

What are the recommended guidelines for organizing files in an NPM package for front-end development?

I am creating an NPM package for the front-end and I'm trying to figure out the optimal file structure. My package consists of a code.js file as well as a code.min.js file. Should these files be located in the root directory, a dist folder, or a src f ...

How to choose a javascript drop down using selenium?

Here is the HTML code for a JavaScript drop-down menu that contains various options, including "All Resumes". I am attempting to select this option using Selenium WebDriver: <div id="resume_freshness_container"> <div class="dropdown_small_wrapper ...

The internet explorer browser does not support the keypress event

i have the following code snippet: <input class="any" type="text" id="myId" name="myName" /> this specific input is using a jquery datepicker plugin.. (http://jqueryui.com/datepicker/) Here is my JavaScript for this element: $('#myId'). ...

Discovering ways to access deeply nested JSON data in Vue JS

i am dealing with JSON data that includes payment information. I am facing issues retrieving the paid_amount and date for both cash_payment and installment_payment. { "response": [ { "status": "sold", "price": "1000 ...

Troubleshooting script error: Dealing with Ineffective Redirects

I am currently using a JavaScript code that allows users to jump to a directory by typing its name. Here is how it functions: If the input field is left empty, the user will be directed to a page called "error.html" which displays the message "This field ...

Developing a custom styling class using JavaScript

Looking to create a custom style class within JavaScript tags. The class would look something like this: #file-ok { background-image: url(<?php echo json.get('filename'); ?>); } Essentially, the value returned from the PHP file (json ...

Obtaining the pathname in a NextJS file like _document.js is a matter of accessing

I'm looking to retrieve the current URL path in my /page/_document.js file. I've created a class and my goal is to implement a conditional statement based on this value. Below is the code snippet (similar to the example provided in NextJS docume ...

Enhancing Share Options in Vue Native App: A Step-by-Step Guide

Can you please advise me on the method to achieve this in vue native? I am aiming for my app to support images, urls, and text inputs. https://i.sstatic.net/yZ68d.png ...

Inject a value sent from response.render directly into the script tag

Below you will find a pug snippet. I am looking for a way to dynamically insert the user value into the chatConfig object. script. var chatConfig = { user : 'foo', pass : 'bar', } When rendering from my Express applicatio ...

Unable to locate the required conditional template for the 'mdRadioButton' directive due to the absence of the 'mdRadioGroup' controller

I am currently working on developing a custom directive that will help me display questions within a survey. Given the multiple types of questions I have, I decided to create a single directive and dynamically change its template based on the type of quest ...

Stop ajax request when select2 is clicked

Is there a way to change the ajax call behavior in select2 drop down items so that it only retrieves data when I start typing in the search box, and not on click of the element? Your guidance on this issue would be highly appreciated. $("#ddlItems").sel ...

Error Encountered on Amazon EC2: Unable to Listen on IP Address 0.0.0.0:80,

Despite adding the HTTP TCP Port 80 to the inbound rules, I am still encountering the following error: Error: listen EACCES 0.0.0.0:80 at Object._errnoException (util.js:992:11) at _exceptionWithHostPort (util.js:1014:20) at Server.setupList ...