Adding a property to every object within an array using Vue.js: A step-by-step guide

Situation: In my data(), I have an array that receives objects from the backend. When the GET request brings back 6 objects, those objects are updated in the array.

Issue: I am aware that vm.$set is necessary to add properties to an object. But how can I add properties to all objects in the array?

I aim to modify:

data() {
    return {
      expenseButton: [{key:value},{key:value},{key:value}]
         };
  }

to

data() {
    return {
      expenseButton: [{key:value, key2:value2},{key:value, key2:value2},{key:value, key2:value2}]
         };
  }

Attempted Solution resulted in newValue being added as a property in the entire array rather than each object

methods: {
    check() {
      this.$set(this.expenseButton, "newValue", this.expenseButton.newValue);
      console.log(this.expenseButton);
    }
  },

UPDATE How can I apply vm.$set to target all objects in an array so that each object has a new property named "newValue"?

data() {
    return {
      expenseButton: [{key1:value1},{key2:value2},{key3:value3}]
         };
  }

TO

data() {
    return {
      expenseButton: [{key1:value1,newValue: ''},{key2:value2, newValue: ''},{key3:value3, newValue: ''}]
         };
  }

Answer №1

Manipulating arrays using $set involves specifying the index where you want to set a new value.

For a more efficient approach, consider mapping over the array items and adding the property directly to each item instead of using $set.

update() {
  this.expenseButton = this.expenseButton.map((obj) => {
    obj.newValue = ''
    return obj
  })
}

To maintain reactivity, ensure to call $set for each index with its corresponding key-value pair. Check out @blex's response for more details.

update() {
  this.expenseButton.forEach((_, index) => {
    this.$set(this.expenseButton[index], 'newValue', '')
  })
}

If this explanation answers your query, kindly mark @blex’s answer as the accepted solution.

Answer №2

To implement this.$set within a loop, follow these steps:

Vue.component('my-component', {
  template: '#my-component',
  data() {
    return {
      expenseButton: [{ key: 0 }, { key: 1 }, { key: 2 }]
    };
  },
  methods: {
    check() {
      this.expenseButton.forEach((obj, index) => {
        this.$set(this.expenseButton[index], "newKey", index * 2);
      });
    }
  }
});

var vm = new Vue({
  el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.min.js"></script>

<div id="app">
  <my-component></my-component>
</div>

<template id="my-component">
  <div>
    <ul>
      <li v-for="item in expenseButton" :key="item.key">
       {{item}}
      </li>
    </ul>
    <button @click="check">Update items</button>
  </div>
</template>

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

I am interested in generating a Stacked Chart in Google Charts using data from a JSON file

Hey there, I'm looking to generate a stacked chart using JSON data in Google Charts. My current challenge revolves around the code snippet var data = google.visualization.arrayToDataTable([. <?php $tmp = array(); require "configdashboard.php"; /* ...

Enable Users to Customize Default Values in a Vue 3 Component Library

I am in the process of building a Vue 3 component library and I want to give users the ability to customize default values for components. To install the library, users will need to follow these steps: // Import styles and library import { mountLibrary } f ...

The concept of 'this' in TypeScript classes compared to JavaScript's scope

Is there a way to change the custom icon of a video when it is toggled between Play and Pause? ngAfterViewInit() { const vdoCont = document.querySelector('.video-player'); const vdo = vdoCont.querySelector('video'); vdo.addEventL ...

Refresh a TextBox using an Ajax Response

Is there a way to dynamically update a textbox with the response from an ajax call? I've managed to get the response and assign it to the textbox using: document.getElementById("testPad").value = xmlHttpRequest.responseText; The issue is that the en ...

Introduction to Java Programming While-Loop for Beginners

In the process of developing a while-loop program for a group of animals whose identity is not known to me, the user is granted the freedom to decide their quantity, but the program will halt once the input "exterminate" is detected. The objective of this ...

Trouble with event.preventDefault() on hyperlinks failing to work

I have searched through numerous topics on Stack Overflow regarding this issue, but none of the suggestions have been able to solve my problem. My specific challenge involves a list of div elements, each containing a hyperlink and a hidden span element wh ...

Exploring search filters using KnockoutJS

I'm currently working on incorporating a search filter into my web application. After reading some informative articles and exploring various Jsfiddles, I've attempted to enable searching by TypeName to display the corresponding row with that spe ...

Detach attention from TextField select component in Material UI and React through manual means

When I create a select input using the TextField component from Material-UI library, I need to manually remove focus after an option is selected. I attempted to achieve this by using a reference to the TextField with the 'inputRef' prop. However, ...

Words of wisdom shared on social media

How can I share text from my HTML page on Twitter? This is the code snippet from my HTML page - function change() { quotes = ["Naam toh suna hi hoga", "Mogambo Khush Hua", "Kitne aadmi the?"]; auth = ["Raj", "Mogambo", "Gabbar"]; min = 0; max = ...

Differences Between Vuex Actions and Mutations

Can you explain the purpose of having both "actions" and "mutations" in Vuex? I comprehend the reasoning behind components not directly modifying state, but what is the advantage of introducing actions that trigger mutations to alter state? It seems like ...

Steps for resetting data() on a route without parameters:

Having trouble restarting a route on a new editor I have a specific route /editor as well as /editor?_id=dasd448846acsca The /editor route consists of a simple form with empty inputs, while the /editor?_id=dasd448846acsca route has the same component bu ...

The functionality of Jquery ceases to work once a setTimeout function is implemented

I need some help getting a series of functions to be delayed by 2 seconds using setTimeout. For some reason, whenever I try to implement this, the code stops executing altogether. I've double-checked the syntax and everything seems fine because it wor ...

Locate the position of an item in JavaScript based on its value

My json contains a lengthy list of timezones like the examples below. [ {"value": "Pacific/Niue", "name": "(GMT-11:00) Niue"}, {"value": "Pacific/Pago_Pago", "name": "(GMT-11:00) Pago Pago"}, {"value": "Pacific/Honolulu", "name": "(GMT-10:00) Hawaii T ...

Automate the vertical resizing of a div element using code

Currently, I am utilizing Angular4+. I am looking to dynamically resize a div vertically, but I am unsure of how to go about it. I am uncertain about where to even begin and how to accomplish this task without resorting to using jQuery. Are there any sugg ...

Tips for effectively scaling controllers in AngularJS

I have an Angular application that is currently structured with everything in one controller. I would like to split it into multiple controllers so that each controller can focus on specific actions rather than having a mixture of functions with different ...

Tips for storing dynamic data in an array using JavaScript

I'm trying to create a loop that will retrieve the href values from certain elements and store them in an array. Can someone help me with this? var linksArray = []; var elements = document.getElementsByClassName("title"); for (var i = 0; i < elem ...

Updating the value of a JSON data attribute

I am looking to update a specific value in a JSON array. To provide more context, here is the DOM structure I have: <input class="fileupload" type="file" data-form-data='{"table_reference": "data_monitoring", "table_token" : "X43sd"}'> I ...

Add transparency to the background color when hovering over inline elements

Initially, my style sheet had the following structure: .button { border-radius: 3px; display: inline-block; padding: 14px 20px; transition: background-color cubic-bezier(0.4, 0.0, 0.2, 1.0) 300ms; &:hover { background-color: transparent ...

Navigating to a particular div using a click event

I am trying to achieve a scrolling effect on my webpage by clicking a button that will target a specific div with the class "second". Currently, I have implemented this functionality using jQuery but I am curious about how to accomplish the same task using ...

ReactJS onClick event not functioning as expected - no action occurs in the browser or in the system console

I've gone through numerous discussions on this issue, but I'm still unable to resolve it. /** @jsx React.DOM */ var React = require('react/addons'); var SegmentComponent = React.createClass({ handleThatEvent: function (e) { ...