[Vuejs]-Append as array inside array

2๐Ÿ‘

โœ…

Iโ€™m just answering this according my assumption of what @senty is trying to do:

pushValue is a method that takes numbers as keys and characters as values and save them into this.types, and whenever pushValue is called, this.types is gonna have a property key storing an object with value as its key, which stores an array containing an empty array. If That array (the one that contains arrays) already exists, another empty is gonna appended to that array. And eventually this.types will look like myObj

Hence, pushValue should look like this:

const app = new Vue({
  el: '#app',
  data: {
    types: {}
  },
  methods: {
    pushValue(key, value) {
      if (this.types.hasOwnProperty(key)) {
        if (this.types[key].hasOwnProperty(value)) {
          const orgValue = this.types[key][value];
          orgValue.push([]);
          this.$set(this.types[key], value, orgValue);
        } else {
          this.$set(this.types[key], value, [[]]);
        }
      } else {
        this.$set(this.types, key, {
          [value]: [ [] ]
        });
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
  <div>
    <p>pushValue(key, value)</p>
    <button v-on:click="pushValue(1, 'a')">(1, 'a')</button>
    <button v-on:click="pushValue(1, 'b')">(1, 'b')</button>
    <button v-on:click="pushValue(1, 'c')">(1, 'c')</button>
    <button v-on:click="pushValue(2, 'a')">(2, 'a')</button>
    <button v-on:click="pushValue(2, 'b')">(2, 'b')</button>
    <button v-on:click="pushValue(2, 'c')">(2, 'c')</button>
  </div>
  <div>{{ types }}</div>  
</div>
๐Ÿ‘คkevguy

Leave a comment