【问题标题】:How to merge properties JavaScript objects如何合并属性 JavaScript 对象
【发布时间】:2019-09-10 01:01:05
【问题描述】:

我从 Vue 开始,但遇到了一点困难。

在下图中,我有一个包含一些项目的表格:

每次选择一个项目并且数量增加时,我需要在我的addOptional 方法(可选)中,我的变量获取该项目的数量与该值连接。例如,如果我选择锤子看起来像这样 `

let variavel = opcional.Qtd + 'x' + opcional.Code

如果我给 console.log 结果将是 2x1

但是如果我选择另一个选项,例如 Serrote,我应该将第一个选项加入同一个变量中,并用 Pipe (|) 分隔,示例如下所示。

2x1 | 1x2

我该怎么做?我应该使用数组吗?

我已经拥有的:

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 }
      ]
    }
  },
  methods: {
    addOpcional(opcional) {
      // 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)
      opcional.Qtd += 1

      let Code = [opcional.Qtd + 'x' + opcional.Code]
      },

    remove(opcional) {

    }
  }
})
<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 ? opcional.Qtd-- : false">-</button>
              <input type="text" :value="opcional.Qtd">
              <button @click="addOpcional(opcional)">+</button>
            </td>
            <td>{{ opcional.Nome }}</td>
            <td>{{ opcional.Valor }}</td>
            <td>{{ opcional.Valor * opcional.Qtd }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </template>
</div>

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    这似乎是computed property 的完美用例:

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

    这是一个完整的工作示例,显示表格下方的代码并实时更新:

    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>

    【讨论】:

    • 非常感谢,这正是我所需要的,别名是一种非常简单的理解方式
    【解决方案2】:

    对 Vue 不太熟悉,但你可以reduce Opcionais 像这样:

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

    【讨论】:

      【解决方案3】:

      您可以使用spread operator 来保留当前状态并添加新项目。 要加入管道,请使用下面回答的“reducer”,或者根据需要在 html 中执行。

      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 }
            ],
            Elements: []
          }
        },
        methods: {
          addOpcional(opcional) {
            // 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)
            opcional.Qtd += 1
      
            this.Elements = [...this.Elements, (opcional.Qtd + 1) + 'x' + opcional.Code]
            },
      
          remove(opcional) {
      
          }
        }
      })
      <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 ? opcional.Qtd-- : false">-</button>
                    <input type="text" :value="opcional.Qtd">
                    <button @click="addOpcional(opcional)">+</button>
                  </td>
                  <td>{{ opcional.Nome }}</td>
                  <td>{{ opcional.Valor }}</td>
                  <td>{{ opcional.Valor * opcional.Qtd }}</td>
                </tr>
              </tbody>
            </table>
            <pre>{{ Elements.join("|") }}</pre>
          </div>
        </template>
      </div>

      【讨论】:

      • 运行您的 sn-p 并单击第一个“+”按钮几次后,我现在在表格下方看到字符串 2x1|3x1|4x1|5x1|6x1|7x1。我可能错了,但我相当确定这不是 OP 正在寻找的。尤其是数量减少了一个。
      • 非常感谢,这正是我所需要的。只需要检查该值是否已经存在,如果是,则仅增加数量不会创建另一个
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-05
      • 1970-01-01
      • 2021-03-29
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      • 2020-07-05
      相关资源
      最近更新 更多