Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Constructing array within vue method

I’m currently sending multiple values through a selection change event in vue, and I’m logging the values within my method call to make sure they exist in the method( they do)

My issue is that I need to take the values within that method and create an array structured like this:

{ "123" : 
   [   
       { "item":"B-24", "new_date":"2022-11-30" },

   ] 
 }

My issue is that I can push the values into an array, but I can’t seem to figure out how to restructure the array to fit the format above.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any suggestions on how to structure the array in the method are much appreciated

var vm = 
new Vue({
  el: "#app",
  props: { 

  },
  data: {
    testing_dates:['2021-11-29', '2021-11-30'],
    cat_id: [123]
  },
  methods: {
    testChange(event, id){
      item = "B-24";

      console.log(event.target.value);
      console.log(id);

      var new_array = new Array(); //create an empty array
      new_array.push(item);
      new_array.push(event.target.value);
      new_array.push(id);
    },
  },
});
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<li>Category ID: {{ cat_id }}</li>
<li style="list-style: none;">
  <select style="width: auto;" @change="testChange($event, cat_id)">
     <option selected disabled>Options</option>
     <option v-for="date in testing_dates" :value="date">{{ date }}</option>
  </select>
</li>
</div>

>Solution :

You can get the first id using restructuring or as id[0].

Then create an empty object and add a new pair to it where the key is the first id and the value is an array with one object having the item and the new_date

testChange(event, id){
  const item = "B-24";
  const [firstId] = id; // get first id
  const obj = {};
  obj[firstId] = [ { item, new_data: event.target.value } ];
  console.log(obj);
}

Shorter version:

testChange(event, id){
  const obj = {
    [id[0]]: [ { item:  "B-24", new_data: event.target.value } ]
  };
  console.log(obj);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading