【问题标题】:Vue how push object with specific key to arrayVue如何将具有特定键的对象推送到数组
【发布时间】:2020-04-07 08:14:58
【问题描述】:

我正在开发一个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...
 ]

现在我想循环遍历数组并根据type-attribute 将它们分开或推送到custom_licensesbasic_licenses - 我该如何实现?

【问题讨论】:

    标签: javascript arrays vue.js vuejs2


    【解决方案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;
        });
      });
    },
    

    【讨论】:

      【解决方案2】:

      更新您的代码块:

       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);
          }  
        });
      

      【讨论】:

        猜你喜欢
        • 2019-05-17
        • 2022-11-02
        • 1970-01-01
        • 2011-08-17
        • 1970-01-01
        • 2019-04-11
        • 2018-08-09
        • 2019-10-04
        • 1970-01-01
        相关资源
        最近更新 更多