[js] Object delete key, scenario: the form copy function only requires a few fields to retain values

Scenario:
Copy button, you can keep the value of the specified field of the form, and delete other fields. When you click Save, it is equivalent to taking the new interface

The previous writing method is similar to this.form.id = '', if there are many form fields, there may be forty or fifty lines of code like this

still want to optimize

Ideas:

Get all the keys of the object, loop the keys, and delete the keys that are not specified fields

Remark:

This.form[item] gets the value corresponding to the key . This.form ['item'] gets the item whose
key is item.
${item}

    // 复制
    confirmClick() {
    
    
      this.$confirm(this.$t('confirmText.copyMsg'), this.$t('confirmText.tip'), {
    
    
        confirmButtonText: this.$t('btnName.confirm'),
        cancelButtonText: this.$t('btnName.cancel'),
        type: 'warning',
      }).then(() => {
        const keyArr = Object.keys(this.form)
        keyArr.forEach(item => {
          if (item !== 'a' && item !== 'b' && item !== 'c') {
            delete this.form[`${item}`]           
          } else {
            this.form.status = 'normal'        
          }
        })
        this.$message.success(this.$t('messageText.copySuccess'))
      })
    },

Guess you like

Origin blog.csdn.net/weixin_49668076/article/details/130259157