Skip to content
Advertisement

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.

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>

Advertisement

Answer

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);
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement