Goms
Goms

Reputation: 2644

How to replace or update item of array in JavaScript

The title describes what I want, this is the code

All is fine when we add a product to items if it doesn't exists (difference by id). But if it exists, I want to modify only the item. The difference is made by id of each item in items array.

Eg : if first, id = 1, qty = 3, and next, id = 1, qty = 3, I want the update of qty in items

new Vue({
  el: '#fact',
  data: {
    input: {
      id: null,
      qty: 1
    },
    items: []
  },
  methods: {
    addItem() {
      var item = {
        id: this.input.id,
        qty: this.input.qty
      };
      
      if(index = this.itemExists(item) !== false)
      {
          this.items.slice(index, 1, item);
          return null;
      }
      
      this.items.push(item)
    },
    itemExists($input){
       for (var i = 0, c = this.items.length; i < c; i++) {
           if (this.items[i].id == $input.id) {
               return i;
          }
       }
       return false;
    }
  }
})
<Doctype html>
  <html>

  <head>
    <meta charset="utf-8" />
    <title>Add product</title>
  </head>

  <body>
    <div id="fact">
      <p>
        <input type="text" v-model="input.id" placeholder="id of product" />
      </p>
      <p>
        <input type="text" v-model="input.qty" placeholder="quantity of product" />
      </p>
      <button @click="addItem">Add</button>

      <ul v-if="items.length > 0">
        <li v-for="item in items">{{ item.qty + ' ' + item.id }}</li>
      </ul>
      
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
  </body>

  </html>

Upvotes: 4

Views: 19695

Answers (2)

akuiper
akuiper

Reputation: 214957

You might have misused the slice method, change slice to splice works for me:

this.items.splice(index, 1, item)

slice doesn't trigger view updates according to the documentation here.

Vue wraps an observed array’s mutation methods so they will also trigger view updates. The wrapped methods are:

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

Upvotes: 6

Rahul Reghunath
Rahul Reghunath

Reputation: 1276

if(index = this.itemExists(item) !== false)
{
    for (let value of this.items) {
        if(value.id === item.id) {
            value.qty = item.qty;
        }
     }

     return null;
 }

Upvotes: -1

Related Questions