[Vuejs]-Push data and key into array in vuejs

1πŸ‘

βœ…

I want to push to the β€˜list’ array of the following format, The key is
info

list: [
info: [
{
name:yorn,
age: 20
} ] ]

The above expected result is not a valid JSON. It should be like below :

list: [{
    info: [{
        name: yorn,
        age: 20
    }]
}]

Working Demo :

new Vue({
  el: '#app',
  data: {
    list: []
  },
  mounted() {
    this.pushData();
  },
  methods: {
    pushData() {
      this.list.push({info : [{name:'yorn', age: 20}] });
      // Or you can also use below one.
      // this.list[0].info.push({name:'yorn', age: 20});
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(obj, index) in list" :key="index">
    <p v-for="(item, i) in obj.info" :key="i">{{ item.name }}       </p>
  </div>
</div>
πŸ‘€Debug Diva

1πŸ‘

Try altering the pushData method to have data parameter

pushData(data) {
 this.list.push(data);
}

Invoke the method

this.pushData({name: "john", age: 25});
πŸ‘€Nader

1πŸ‘

As I understand, you are trying to create a nested array. However, in an array you don’t use a key but an index. What you are looking for is called an associative array.

Option a: Use the index of a β€˜normal’ array

list = [{name: 'abc', age: 10},{name: 'def', age: 20}]

This way you can use the data in your array by using the index:

list[0] == {name: 'abc', age: 10}

list[1] == {name: 'def', age: 20}

Option b: Use an associative array

list = { info1: {name: 'abc', age: 10}, info2: {name: 'def', age: 20}}

This way you can use a key instead of an index. You just need different brackets for an associative array.

Hope this is helpful. πŸ™‚

πŸ‘€EduDev

1πŸ‘

You can simply use like below

pushData() {
 let data = { info : [{name:'yorn', age: 20}] }
 this.list.push(data);

}

Hope this is helpful. πŸ™‚

πŸ‘€rohithpoya

Leave a comment