Thiago Guimarães
Thiago Guimarães

Reputation: 73

How do I create unique keys/replace its value with array.push?

I have dynamically generated inputs and I need to add them to an array.

data(){
    return{
     picture: []
   };
}

I have this in my template:

  <ion-input  :ref="'picture'+n" :id="'picture'+n" @change="getPicture" accept=".jpeg, .png, .jpg" type="file"></ion-input>

I need to get the inputs in the correct order, so I created an associative array, passing the id of each input to the key:

getPicture(e: any){
  const pictureInput=e.currentTarget.id;
  this.picture.push({[pictureInput]: e.target.files[0]}); 
}

This works, however, if I want to change a file in an input that already has a file, a new array is added with the same key and I would like the keys to be unique.

So my question is:

Is there any way to replace the value of the key that already exists instead of adding a new array with the same key name?

Upvotes: 0

Views: 98

Answers (3)

Asimple
Asimple

Reputation: 650

You can pass both event data and key.
More info about this here
Example:

const app = new Vue({
  el: '#app',
  data: {
    inputs: [{
        file: null
      },
      {
        file: null
      },
    ]
  },
  methods: {
    eventHandler(key, e) {
      this.inputs[key].file = e.target.files[0];
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(input, index) in inputs" :key="'name-' + index">
    {{index}} - {{input.file?.name}}
  </div>
  <br/>
  <input
    v-for="(input, index) in inputs"
    type="file"
    :key="'picture-' + index"
    @change="eventHandler(index, $event)"
  />
</div>

Upvotes: 1

Shubham P
Shubham P

Reputation: 1292

The simplest way will be to use an if-else here - enter image description here

getPicture(e: any){
  const pictureInput = e.currentTarget.id;
  // Check if same key is already pushed
  let targetEntry = this.picture.find(e => e[pictureInput] !== undefined);
  if(targetEntry){
    // already exists REPLACE
    targetEntry[pictureInput] = e.target.files[0];
  }
  else{
    // already exists PUSH
    this.picture.push({[pictureInput]: e.target.files[0]}); 
  }
}

Upvotes: 1

Babacar C. DIA
Babacar C. DIA

Reputation: 420

You can use the array index

  • when looping
<div v-for="(item, itemIndex) in items" :key="itemIndex">
  <img :src="item.src"/>
  <button @click=removeItem(itemIndex)>delete</button>
</div>
  • when removing item
  removeItem (index) {
    this.items.splice(index, 1)
  }

Upvotes: 1

Related Questions