V
V
Vasya Surname2020-11-05 03:39:31
Vue.js
Vasya Surname, 2020-11-05 03:39:31

How to update the value in an array element?

Given this json array

inputs: [
      { label: 'Продавец', label1: 'Покупатель', type: 'text', name: 'seller'},
      { label: 'Полное наименование продавца', label1: 'Полное наименование покупателя',  type: 'text', name: 'fullname'},
     ]

after clicking I call an event where such a function

this.inputs.forEach((value, index) => {
  this.$set(this.inputs, index, {label: value.label1})
});

Everything works, but the problem is that the entire line of the array is reset to zero
. That is, only the label remains, and type and text disappear.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Gololobov, 2020-11-05
@bazilio2010

If you want to do exactly as you have written, then here is an option:

this.inputs.forEach((value, index) => {
  this.$set(this.inputs, index, {...value, label: value.label1})
});

But I would do it differently. If i need to replace label with label1 from same element in all array elements.
You can, for example, unmap the entire array. And in theory, you don’t even need set:
this.inputs = this.inputs.map(item => ({ ...item, label: item.label1 }))

In your version, as I understand it, the component will be drawn whenever you change an array element. In my version, drawing will happen once, only after the entire array has been updated.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question