Integrate fresh data into an array using Vue

Exploring VUE for the first time, I am working on a project where I need to update an array by passing an object. The scenario involves two buttons named BUTTON 1 and BUTTON 2. Clicking on BUTTON 1 sets an object in the list[] using this.$set. However, when BUTTON 2 is clicked, it should update with a new value and display as:

{
 a:1,
 b:2,
 c:3
}

Currently, I am using this.$set for button 2 as well, which replaces the previous value with the new one like {c:3} only. Is there a way in VUE to add on the value so that it displays {a:1, b:2, c:3} when BUTTON 2 is clicked?

View

<div id="app">
  <button @click="button1()">Button 1</button>
  <button @click="button2()">Button 2</button>
</div>

Method

new Vue({
  el: "#app",
  data: {
    list:[]
  },
  methods: {
    
    button1(){
      var b = '0';
      this.$set(this.list, b, {
        1:{
            a: '1',
            b: '2'
        }
      })
      console.log(this.list);
    },
    
    button2(){
      var b = '0';
      this.$set(this.list, b,{
        1:{
            c: '3'
        }
      })
      console.log(this.list);
    },
    
  }
})

Above code can be accessed via the following jsfiddle link:

https://jsfiddle.net/ujjumaki/enj3dwo6/19/

Answer №1

Let's hope this solution does the trick!

new Vue({
el: "#app",
data: {
items:[]
 },
 methods {

clickButton(){
console.log('Clicked button');

const index = '0';
const remainingData=this.items[index] && this.items[index][1]
    this.$set(this.items, index, {
    1:{
    ...remainingData,
        x: '4',
        y: '8'
    }
  })
  
  console.log(this.items);
},

pressButton(){

const index = '0';
const remainingData=this.items[index] && this.items[index][1]
    this.$set(this.items, index,{
    1:{
    ...remainingData,
        z: '12'
    }
  })
  
  console.log(this.items);
},

}
})

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

"Retrieving Data Using jQuery's .ajax Method in Visual Basic

<WebMethod()> Public Shared Function gtet() As String ... Dim GET = uClass.GetSets(dbuser, dbparam1) ... End Function and $(document).ready(function () { data = { }; var jsondata = $.toJSON(data); $.ajax({ type: "GET ...

The width of Material UI Grid decreases every time it is re-rendered

I'm attempting to display a list of 25 words in a 5x5 grid using the MUI Grid component. The grid is structured as a <Grid container direction="column"> with five <Grid item> elements. Each <Grid item> contains: <Grid co ...

Tips for extracting and mapping a sub array from the category response JSON using SWR with MongoDB in a Next.js (Node.js) environment

Can anyone assist me with reading and mapping arrays inside JSON? Using Hook (useSWR / useCategories): import useSWR from "swr" const fetcher = (...args) => fetch(...args).then(res => res.json()) function useCategories () { const { data, erro ...

Tips on preventing users from navigating backwards in a React Redux application

Seeking guidance on how to restrict user access after successful login in react redux. Can anyone assist me? I want to prevent users from navigating back to certain routes once they are logged in I am currently working on securing the routes to block unau ...

How can I use jQuery to hide each div of the same class individually when a user clicks on each div to close

I am working on a project where I have multiple notification boxes represented by divs with the same class. These boxes are set to fade in one after the other using jQuery. Each box also contains a 'close_box' div that acts as a button to close/h ...

What can be done to ensure smooth functionality of my nested navigation menu on mobile devices?

I'm utilizing the incredible features of Base Web for my website. One of the components I am using is a menu with a child menu, based on this example. The menu works perfectly fine on desktop - when I hover over an option, the child menu appears. Howe ...

Tips on choosing a child element with a parameter in React

Is it possible to pass a parameter in my function and use it to select a child of my JSON parse? I want to create a function (checkMatch) that can check if a username in my database matches with the input value. It should return 1 if there is a match, oth ...

Chrome can't locate VueJS locally

Recently, I encountered an issue where when trying to access http://localhost:8080/ in Chrome, I was redirected to a bad request page generated by the browser itself. However, if I accessed the network URL, for example, http://192.168.1.1:8080/, Chrome loa ...

Using jQuery to refresh a div element

I am struggling with updating the "right" div in my jsp page using the script below. Despite being contained in a single file, the update does not seem to work. Any assistance is appreciated. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//E ...

Is it possible to compile TypeScript modules directly into native code within the JavaScript data file?

I am seeking a way to break down an app in a TypeScript development environment into separate function files, where each file contains only one function. I want to achieve this using TS modules, but I do not want these modules to be imported at runtime in ...

Steps for implementing a conditional statement to handle an empty string in HTML

I need to figure out how to display a different message if my string is empty. Can anyone help me with this? <div class="padding" id="dealBorder"> <pre id="informationDealText"><pan class="inner-pre" style="font-size: 24px; color: whi ...

Update the icon with the adjusted API information

I am currently working on a website that revolves around the theme of weather. I have reached a point in the development process where I need the icon to change according to the current weather conditions. let updateIcon = () => { let ic ...

Converting a class-based component into a functional component

TL;DR : I am in the process of converting my class-based App component to a Functional component but encountering unexpected outcomes with the useEffect Hook. Being relatively new to React, I originally built my movie search app using a class-based approa ...

Edit CSS attributes within Angular 2+ framework

When using jQuery, we have the ability to do the following: JQuery('.someStyle') .css({"background", "red"}) This allows us to directly change the CSS property in style. While working with Angular 2+, we can use [style.<property>] for ...

React-hook-form does not display the input length in a custom React component

Introducing a custom Textarea component designed for reusability, this basic textarea includes a maxlength prop allowing users to set the maximum input length. It also displays the current input length in the format current input length/max length. While ...

Node.js local storage/cookie functionality

Running three different apps on Node.js at ports 3000, 3005, and 3007. I need to set a LocalStorage or Cookie variable at port 3000 and access it from the apps running at ports 3005 and 3007. Folder structure: nodep/ |-app.js (runs at port 30 ...

The PayPal checkout component in Vue remains in sandbox mode

I've been facing challenges when trying to transition to the live environment. It's perplexing how everything seems to function seamlessly in sandbox mode, yet there appears to be no clear guidance on switching to production or it simply doesn&ap ...

Activate a button on-the-fly

When the page loads, I have an empty array. Since there are no values stored in this array, I disabled the button using ng-disabled="array1.length==0". Now, on the page that opens up, there are four drop downs present. My goal is to enable the button once ...

When using jQuery, the search for the ID within an iframe may fail if the specified condition

I have a scenario where I need to dynamically generate an iframe and its corresponding id. Now, I need to check if the generated id already exists or not. This is what my code looks like: function createIframe(intxnId){ alert("The Id is : "+"$(&apo ...

Built-in Promises within MongoDB

Is there a way to determine which methods in mongoDb have an inbuilt promise? For example, "updateOne() , findOne()" have inbuilt promises that we can access using ".then", but many other mongoDB methods lack this feature. How can we identify which methods ...