Home > Mobile >  How to insert a value inside a particular array of object
How to insert a value inside a particular array of object

Time:12-01

I am using Vue (vuetify) v-data-table to show some data, Its working fine, in the same time I am trying to show some data from another api, So I need to know how to push a items inside of a array of object.

axiosThis.tableDataFinal[i].push(axiosThis.printsumget[i])

I am getting an error .push is not a function

CodePudding user response:

try this code

const array = [
        {
            id: 1,
            name: 'hp'
        }, {
            id: 2,
            name: 'hp'
        }

    ]
    array.map((item) => {
        if(item.id === 1){
            array[0]['InnerArray'] = [1, 2, 4]
        }
    })

CodePudding user response:

As per your code, Looks like you are trying to perform a push operation on an object instead of an array. That's the reason it is giving you that error.

Also, As per my understanding. Your API response will give you an array of objects. So instead of using .push, You can use Destructuring assignment

Live Demo :

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      headers: [
        {
          text: 'Dessert (100g serving)',
          align: 'start',
          sortable: false,
          value: 'name',
        },
        { text: 'Calories', value: 'calories' }
      ],
      desserts: [
        {
          name: 'Frozen Yogurt',
          calories: 159
        },
        {
          name: 'Ice cream sandwich',
          calories: 237
        }
      ]
    }
  },
  mounted() {
    // Another axios api call. Just for a demo purpose I am using mock array here. You can replace it with an actual API response.
    const res = [{
      name: 'Burger',
      calories: 200
    }, {
      name: 'Chocolate Cake',
      calories: 250
    }];
    this.desserts = [...this.desserts, ...res];
    }
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vuetify.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/vuetify.min.css"/>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900"/>
<div id="app">
  <v-app id="inspire">
    <v-data-table
      :headers="headers"
      :items="desserts"
      :items-per-page="5"
      
    ></v-data-table>
  </v-app>
</div>

  • Related