A guide on iterating through an array in vue.js and appending a new attribute to each object

To incorporate a new property or array item into an existing virtual DOM element in Vue.js, the $set function must be utilized. Attempting to do so directly can cause issues:

  • For objects:
    this.myObject.newProperty = "value";
  • For arrays: this.myArray[3] = object;

The correct way to accomplish this is as follows:

  • For objects:
    this.$set(this.myObject, "newProperty", "value");
  • For arrays:
    this.$set(this.myArray, 3, object);

An issue may arise when trying to set a property for all objects within an array using a loop:

for (var i = 0; i < this.myArray.length; i++) {
    this.myArray[i].newProperty = "value";
}

If you wish to utilize $set to modify properties of all objects within an array, what method should be employed?

Answer №1

Your code has been slightly adjusted and it now works as intended:

new Vue({
  el: "#app",
  data: {
    todos: [{
        text: "Learn JavaScript",
        done: false
      },
      {
        text: "Learn Vue",
        done: false
      },
      {
        text: "Play around in JSFiddle",
        done: true
      },
      {
        text: "Build something awesome",
        done: true
      }
    ]
  },
  methods: {
    toggle: function(todo) {
      todo.done = !todo.done
    },
    changeProperty1() {
      const val = 'A'
      // This part of the code has been optimized for efficiency
      for (var i = 0, length = this.todos.length; i < length; i++) {
        this.$set(this.todos[i], 'property1', val);
      }
    },
    changeProperty1Again() {
      for (todo of this.todos) {
        if (todo.property1) {
          todo.property1 = 'B'
        }
      }
    }
  },
  created() {

  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <h2>Todos:</h2>
  <ol>
    <li v-for="todo in todos">
      <label>
        <input type="checkbox"
          v-on:change="toggle(todo)"
          v-bind:checked="todo.done">

        <del v-if="todo.done">
          {{ todo.text }}
        </del>
        <span v-else>
          {{ todo.text }}
        </span>
        <span>
          {{ todo.property1 }}
        </span>
      </label>
    </li>
  </ol>
  <button @click="changeProperty1">Click this first</button>
  <button @click="changeProperty1Again">Click this second</button>
</div>

I apologize for the long snippet, I just copied it over from JSFiddle :)

Answer №2

When you find yourself repeatedly using

this.$set(this.myArray, 3, object);
in a loop with an index, consider making modifications to your object like this:

var newObject = Object.assign({}, this.myArray[i], {newProperty: 'value'} ); // Create an immutable object
this.$set(this.myArray, i, newObject);

However, keep in mind that calling $set for each iteration can be inefficient. A more efficient approach would be to use the map function to create a new object within the array:

const newArray = myArray.map(object => {
   return Object.assign({}, object, {newProperty: 'value'} );
   //or by ES6 spread operator
   return {...object, newProperty: 'value'};
});

After updating the array, trigger Vuejs to re-render the changes.

This alternative method should provide a better solution, but remember to consider how your specific context may affect the implementation!

Answer №3

If you're looking to enhance objects within an array by adding new properties, rather than replacing values within the array based on their index, you can achieve this with the following technique:

new Vue({
    el: '#demo',
    data: {
        myArray: [
            {id: 1},
            {id: 2},
            {id: 3},
            {id: 4},
            {id: 5}
        ]
    },
    methods: {
        addProperties() {
            for (var i = 0; i < this.myArray.length; i++) {
                this.$set(this.myArray[i], 'newProperty', 5 - i)
            }
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
    <div v-for="item in myArray" :key="item.id">
        <span>{{item.id}}: </span>
        <span v-if="item.newProperty">{{item.newProperty}}</span>
    </div>
    <button @click="addProperties">Add Properties</button>
</div>

Answer №4

This technique doesn't directly involve Vue, but rather relies on vanilla JavaScript:

arr.map(item => { return {...item, additionalProperty: "similarValueToRest"}});

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

Unable to access the attributes of the mongoose model

I'm experiencing an issue with my mongoose model.find code below Displayed here is my node.js code that utilizes mongoose to interact with MongoDB. However, upon running it, I encounter the following error message: Starting... (node:7863) Unhandl ...

The v-data-table is unable to fetch the user list information from the API using Axios

How can I solve the issue of displaying "No data available" in the user list data table on my userDirectory page? I have created a userDirectory page with a subheader and a data table from Vuetify, but it seems to have no data available. <template> ...

Struggling to locate the element value in Puppeteer? Reach out for assistance with await page.waitForSelector() or await page.waitForXPath()

insert image description here[ await page.waitForSelector('.DateRangeSelectorstyles__DateInput-sc-5md5uc-2.kXffji.sc-cSHVUG.VGFsW'); await page.type('.DateRangeSelectorstyles__DateInput-sc-5md5uc-2.kXffji.sc-cSHVUG.VGFsW','01- ...

Discover how to access all of the response headers from an HTTP request in Angular

Currently, I am utilizing HttpClient to make a request for a `json` file. My intention is to have the file cached using `ETag`, however, this feature does not seem to be functioning as expected. Upon investigation, it appears that the absence of sending of ...

Adjust rankings based on the number of upvotes received by a project

I'm facing a challenge with ranking projects based on the number of votes they receive. No matter the vote count, the project always ends up getting ranked as 1. To address this issue, I developed a function to manage the rank count and a return hand ...

What is the best way to interpret a nested JSON object?

Recently I've crafted an object that looks like this. myObj = { "name":"John", "age":30, "cars": [ "car1":"Ford", "car2":"BMW", "car3":"Fiat" ] } While it's pretty straightforward to read the name and age properties, I find ...

Leverage JSON data and implement it in JavaScript

In my PHP page, I have a JavaScript function that includes a JSON method for retrieving data from the database. The code snippet looks like this: $this->registerJsFile('/js/restaurant-reserve.js', ['depends' => [JqueryAsset::class ...

The error message "Express Routing - Attempting to access property 'include' of undefined" is displayed when an

I am attempting to implement basic routing based on the user's selections on the first page. If the user picks 2 out of 3 options on the parent page, I want them to only see those two child pages and not the third. My strategy for the parent page was ...

Prevent automatic merging of JSON data with identical IDs

My AJAX call to a PHP select request is as follows: $.ajax({ type: "POST", url: "/renforts/_getIntervenantManager", data: { IDMission : IDMission, IDManager : IDManager }, dataType : 'json' ...

Converting coordinates to pixel-based fixed positioning in CSS

After creating an animated square pie chart using basic CSS to display it in a grid format, I am now looking to transform the larger squares into a state map grid. Any ideas on how to achieve this? In my JavaScript code snippet below, I believe there is a ...

Conceal the div containing all its content within

I need to hide a div with all the content inside it using this code: <form action="" method="POST" name="form"> <p for="name">text :</p><input type="text" name="name" value="<?php echo $name_g; ?>" onfocus="ClearPlaceHolder (thi ...

Guide on how to manage the ROW_CLICK event in a module using vue-tables-2 (vuex)

In my project, there is a module called "csv" responsible for handling csv files, and I am using vue-tables-2 along with vuex: Store setup: -store -modules -csv.js -index.js index.js: Vue.use(Vuex) const store = new Vuex.Store({ modul ...

Switches in a React-Native ListView are not refreshing properly

Situation: I encountered an issue with a ListView of Switches Problem: The Switches are not changing state when pressed. When debugging, each switch appears to be checked momentarily after the setValue function is called, but then reverts back to unchecked ...

Generating a new object using an existing one in Typescript

I received a service response containing the following object: let contentArray = { "errorMessages":[ ], "output":[ { "id":1, "excecuteDate":"2022-02-04T13:34:20" ...

Leveraging Selenium to dismiss a browser pop-up

While scraping data from Investing.com, I encountered a pop-up on the website. Despite searching for a clickable button within the elements, I couldn't locate anything suitable. On the element page, all I could find related to the 'X' to cl ...

Which of the two async functions will be executed first?

const [counter, setCounter] = useState(0) Consider the scenario where we have two asynchronous functions, func1 and func2, both of which are responsible for updating the counter state. It is specified that func1 is supposed to execute before func2. async ...

Sorting JSON data using JQuery Ajax

I've encountered an issue with sorting JSON data. Here is the JSON data I'm working with: [ { nom: "TERRES LATINES", numero: "0473343687", image: "http://s604712774.onlinehome.fr/bonapp/api/wp-content/uploads/2016/12 ...

Trouble arises when selecting shapes in Angular 6 with FabricJS

Currently, I am experimenting with fabricjs and drawing different shapes. Interestingly, when I draw the shapes, they appear accurately on the canvas. However, when I try to switch to selection mode, I encounter an issue where I am unable to select the ind ...

This route does not allow the use of the POST method. Only the GET and HEAD methods are supported. This limitation is specific to Laravel

I am encountering an issue while attempting to submit an image via Ajax, receiving the following error message: The POST method is not supported for this route. Supported methods: GET, HEAD. Here is the Javascript code: $("form[name='submitProfi ...

Obtain an indeterminate value from a variable

My situation involves a dynamic variable assigned from a service, requiring a real-time calculator to update another variable using its value. Below is the relevant code snippet: $scope.getSubTotalSCTax = function(){ TableService.checkOut('SubTo ...