SoFunction
Updated on 2025-04-05

How to add new objects to arrays and assign values

Add new objects to the array and assign values

Method 1

There is only one set for arrays

listData: [{name:"Zhang San",age:18}],
//Add objects directly="male"

Method 2

Applicable to multiple sets of information in an array

listData:[],
list:[{"Zhang San","Li Si"}]
//For example, if you want to add the values ​​listed in another array to this array   for (let index = 0; index < ; index++) {
          ({ name: "" });
          [index].name= [index];
        }

The pitfalls and solutions that have been struck by array assignment

Recently, we need to complete dynamic array assignment operations in Vue. After getting the data from the server, we refresh the data in the array, but we found that no matter what method we use, we found that the data cannot be executed downwards here, and no exceptions were reported. In the end, the problem was solved, and a record was made here.

There is still a difference between array assignment in Vue and assignment in normal JS.

  • The following operations can cause the interface to refresh: push, pop, unshift, shift, reverse, sort, splice
  • The following operations will not cause the interface to refresh: slice, concat, filter

Another thing to note:

If you directly assign or change the length, the interface cannot be refreshed.

(1) Set items directly through indexes.

(2) Modify the array length, =3

Second, one problem needs to be paid attention to when obtaining data from the server: the change of the subject object.

For example, after using the axios object to initiate a request, you need to pay attention to processing data in the return method:

Note that when calling objects in the then method of axios, this object cannot be used, because this object refers to an axios instance, so the data data in the vue instance cannot be obtained through this. A value must be used in the outside world to point to the vue instance object. Assigning values ​​through this external object is correct.

var self;
created:function(){
self = this;
},
mouted:function(){        
({
        baseURL: 'url',
        timeout: 10000,
        headers: { 'Content-Type': 'application/json' }
      }).get('xxxxxxxxxx')
          .then(function(response){
            if(>0){
              var datalist = ;
              for(var i=0;i<;i++){
                ({devicetype:datalist[i].name});
              }
            }
        })
          .catch(function(error){
            ((error));
          });
}

The above is personal experience. I hope you can give you a reference and I hope you can support me more.