Tips for updating or replacing items in a JavaScript array

Explaining what I need, here's the code snippet:

Everything works smoothly when adding a product to the items array if it does not already exist (based on id). However, if it does exist, I only want to update the item. The distinction is based on the id of each item in the items array.

For example: if first, id = 1, qty = 3, and then next, id = 1, qty = 3, I wish to update the quantity 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>
            

Answer №1

It appears that there was a confusion with the slice method, but changing it to use splice instead seems to resolve the issue:

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

The documentation states that slice does not trigger view updates, unlike other mutation methods such as `push()`, `pop()`, `shift()`, `unshift()`, `sort()`, `reverse()`.

Vue ensures that changes in observed arrays trigger view updates. The specific wrapped array mutation methods for this purpose are:

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

Answer №2

if(this.locateItem(index) !== false)
{
    for (let item of this.items) {
        if(item.id === index) {
            item.quantity = index.quantity;
        }
     }

     return null;
 }

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

VIDEOJS ERROR: A peculiar mistake has occurred. TypeError: The property 'value' cannot be read since it is undefined in the context of

Recently, I came across a fascinating plugin called videojs-thumbnails for video.js, and I'm eager to incorporate it into my angular component. However, I keep encountering an error that says: VIDEOJS: ERROR: TypeError: Cannot read property 'val ...

Is there a way to modify the color of the horizontal line within react-native-otp-inputs in the React Native platform?

Is there a way to customize the color of the horizontal line in react-native-otp-inputs for react native? I used react-native-otp-inputs to capture user OTP input, but now I want to change the color of the default black horizontal line to white. You can re ...

Modify the perspective with a computed property

In my ViewControls component, I have switchControls that allow me to determine the index of a clicked button. For example, if I click the first button, the snippetValue will be 0 and so on. <template> <SwitchControls v-model="snippetValue&quo ...

I'm struggling to retrieve data from my table using Bootstrap pagination in VueJS 2

I am trying to display data from my API in a table with pagination and filtered results. I have noticed that when I place the function in methods, I am able to retrieve the data from (event-1). However, when I move the function to items in computed, inst ...

Error: ajax is not defined and needs to be declared (repeated twice)

Currently, I have a form that requires processing using Ajax. <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script> <div class="column1"> <form class="form box" action="javascript:networkCheck();" ...

Utilize express compression in Node.js to compress JSON data from the REST API endpoint

I recently developed a small RESTful application using Node.js. I attempted to compress the JSON data returned by an API request using Express and compression, but unfortunately it did not work as expected. var express = require('express'); var ...

Enhancing the functionality of an existing framework through the integration of a

My coding style involves a lot of ASP.NET MVC and jQuery, particularly with ajax calls that return json. Lately, I've been tinkering with organizing my code structure by creating an object within the global object which contains success and fail callb ...

Utilize conditional styling in Vue using CSS

I am having difficulty implementing a conditional Vue statement to change the CSS style based on the text value. Despite trying other tutorials, I have had no success due to my limited experience with Vue. For example, if I want the class to be "is-succes ...

Setting a default value in Vue props if it doesn't pass validation: A guide

Is it possible to assign a default value to a prop using a validator? For instance, if the current prop does not pass the validator and is less than 3, I would like to automatically set the value to 1. Here's an example: currentStep: { type ...

Response text from AJAX in PHP

I am working on an AJAX sign up form and I would like to incorporate a gear wheel animation similar to this When the server successfully signs up a user, I want a specific bar to change to green. To achieve this, I have echoed the names of the functions I ...

Encountering a problem where PDF is displaying squares instead of text while using ReactDOM.createPortal to

Currently, I'm working on a React application where I am using createPortal in ReactDOM to open certain components in new windows. Everything seems to be functioning correctly, except when I try to render PDF files. Strangely, everything works fine wh ...

The NestJS HttpException class will default to a status code of 201 if no specific status code is

This particular instance showcases how instantiating the HttpException class in this manner results in an exception being thrown with an undefined status, ultimately becoming a status of 201 (I presume it defaults to this status as it is associated with a ...

What is the correct way to define an abstract method within a class to ensure that an IDE detects and notifies if the abstract method is not implemented

Is there a way to properly define an abstract method in an abstract class and have the IDE notify us if we forget to implement it? I attempted the following approach, but it did not work: export abstract class MyAbstractClass { /** * @abstract ...

Leveraging ES6 Generators for Efficient XMLHttpRequests

My goal is to simplify AJAX calls using ES6 generators, but I've encountered some issues: let xhr = new XMLHttpRequest() function *statechange() { yield xhr.readyState; } let gen = statechange(); xhr.open("GET", myUrl, true); xhr.onreadystatec ...

Ways to refresh a page after clicking a button inside the modal box

As a beginner in PHP and JavaScript, I am facing an issue with refreshing the page view_create_journals.php when clicking on the change button in the modal. I have added a function to the change button but it doesn't seem to be working. I'm reall ...

Utilizing React Hook to fetch initial data in useEffect

Encountered a roadblock while attempting to update a hook when the web socket is triggered with new data. I noticed that the hooks are returning the default values I initialized them with inside my useEffect, whereas during rendering it shows the correct v ...

Troubleshooting Vuetify's CSS problems related to responsiveness while utilizing Vue-Split-Panel and customizing select border appearance

Currently facing a range of CSS issues with Vuetify that I'm hoping to get some help resolving. Utilizing a split panel view (vue-split-panel) with Vuetify, there seems to be an inconsistency in triggering the full-column width when needed. It's ...

Enhancing Bootstrap Carousel with various effects

My exploration of the web revealed two distinct effects that can be applied to Bootstrap Carousel: Slide and Fade. I'm curious if there are any other unique effects, such as splitting the picture into small 3D boxes that rotate to change the image? ...

Reactjs implemented with Material UI and redux form framework, featuring a password toggle functionality without relying on hooks

Currently, I am working on a react project where I have developed a form framework that wraps Material-UI around Redux Form. If you want to check out the sandbox for this project, you can find it here: https://codesandbox.io/s/romantic-pasteur-nmw92 For ...

What could be causing my array to update when the method is called live but not during unit tests?

One of my methods is called toggleSelect which adds and removes items from an array named selectedItems. This method functions perfectly when I test it live in the browser. However, when running unit tests, it does not seem to work as expected. Despite cal ...