Home > Enterprise >  Push data and key into array in vuejs
Push data and key into array in vuejs

Time:03-12

I have a array in data() :

data()  {
  return {
    list: [],
 }
},

methods: {
  pushData() {
     this.list.push({name:'yorn', age: 20});
  }
}

Now I want to push to the 'list' array of the following format, The key is info:

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

I'm new to vuejs and javascript so I need everyone's help. Please give me your opinion. Thanks

CodePudding user response:

Try altering the pushData method to have data parameter

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

Invoke the method

this.pushData({name: "john", age: 25});

CodePudding user response:

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. :-)

  • Related