How to dynamically extract data from vue object for a POST request to backend?

半世苍凉 提交于 2020-04-17 20:29:09

问题


I have a vue object with all these getters and setters, here is a screenshot from the console.log:

The structure of the actual DATA (the not-vue stuff) looks like this:

       {
          Internal_key: "TESTKEY_1",
          extensiontable_itc: {
            description_itc: "EXTENSION_ITC_1_1",
            description_itc2: "EXTENSION_ITC_1_2",
          },
          extensiontable_sysops: {
            description_sysops: "EXTENSION_SYSOPS_1"
          }
        }

The data might look different in other usecases. There might be more or less key-value pairs on the outer object, and the keys might be named differently as well. Same goes for the nested objects and their contents.

Is there some convenient way to extract this data into a plain JS Object? If not, how can I best loop the vue object to extract the data "manually"? The AJAX request shall be performed by an axios request, if this is important as well.

EDIT: Here is the relevant data in vue:

data() {
  return {
    editingRecord: {
        original: null,
        copy: null
      }
  }
}

During my programflow, both editingRecord.orginal and editingRecord.copy receive data from an inputform. copy sets its data to original if the user clicks the save/send button. Then, I want to take the data from editingRecord.original with both its keys and values and send them to the server via AJAX request.


回答1:


Its best not to mix jQuery with Vue so here's how you would do it using Axios https://github.com/axios/axios

methods: {
    submit() {
      const body = this.editingRecord.original

      // make changes to body

      axios.post( "backend_url", body )
      .then(function(resp){
        console.log(resp)
      });

    }
  }



回答2:


Okay, I found the solution.

  let vueObject = Object.entries(this.editingRecord.original)

  for(const[key, value] of vueObject){
    if(typeof value == 'object' && value !== null){
      for(const [nestedKey, nestedValue] of Object.entries(value)){
        result[nestedKey] = nestedValue
      }
    }else{
      result[key] = value
    }
  }
  console.log("resultObject is", result)

This way you can iterate over all properties including the properties of nested objects and reassign both key and value to a fresh, one-dimensional array.



来源:https://stackoverflow.com/questions/60754724/how-to-dynamically-extract-data-from-vue-object-for-a-post-request-to-backend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!