Vue如何将具有特定键的对象推入数组

时间:2020-04-07 08:14:58

标签: javascript arrays vue.js vuejs2

我正在开发vue应用程序,其中有用于驾驶执照的组件。

我有以下内容:

data() {
   return {
     custom_licenses: [],
     basic_licenses: []
   }
}

在我的方法中,我有这个:

regular_licenses() {
  this.$store.dispatch("license/read").then(response => {
    response.licenses.map((license, key) => {
      // PUSH LICENSES WITH TYPE 'BASIC' TO this.basic_licenses
      // PUSH LICENSES WITH TYPE 'CUSTOM' TO this.custom_licenses
    });
  });
},

在我的created()中,我有这个:

created() {
   this.regular_licenses()
}

我的调度响应,返回以下内容:

licenses: 
 [
   {
     id: 1, 
     type: 'basic', 
     name: 'AMa'
   },
   {
     id: 2, 
     type: 'basic', 
     name: 'A2'
   }, 
   {
     id: 3, 
     type: 'basic', 
     name: 'C'
   },
   {
     id: 4, 
     type: 'custom', 
     name: 'C1'
   }, 
   {
     id: 5, 
     type: 'custom', 
     name: 'D'
   },

   and so on...
 ]

现在,我想遍历数组,并根据custom_licenses属性将其分离或推入basic_licensestype中,我该如何实现?

2 个答案:

答案 0 :(得分:1)

尝试一下

regular_licenses() {
  this.$store.dispatch("license/read").then(response => {
    response.licenses.map((license, key) => {
      switch (license.type)
        case 'basic':
          this.basic_licenses.push({ ...license });
          break;
        case 'custom':
          this.custom_licenses.push({ ...license });
          break;
    });
  });
},

答案 1 :(得分:0)

更新您的代码块:

 response.licenses.map((license, key) => {
   // PUSH LICENSES WITH TYPE 'BASIC' TO this.basic_licenses
    if(license['type'] == 'basic') {
        //deep clone
        let tmpLicense = JSON.parse(JSON.stringify(license));
        basic_licenses.push(tmpLicense);
    } else if(license['type'] == 'custom') {
    // PUSH LICENSES WITH TYPE 'CUSTOM' TO this.custom_licenses        
        //deep clone
        let tmpLicense = JSON.parse(JSON.stringify(license));
        custom_licenses.push(tmpLicense);
    }  
  });
相关问题