如何从vue对象动态提取数据以向后端发送POST请求?

问题描述:

我有一个包含所有这些getter和setter的vue对象,这是console.log的屏幕截图:

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

实际DATA(不重要的东西)的结构看起来像这样:

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.

是否有一些方便的方法可以将这些数据提取到普通的JS对象中? 如果没有,如何最好地循环vue对象以手动"提取数据? AJAX请求也应由axios请求执行,如果这也很重要的话.

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.

这是vue中的相关数据:

Here is the relevant data in vue:

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

在我的程序流程中,editingRecord.orginaleditingRecord.copy都从输入表单接收数据.如果用户单击保存/发送按钮,副本会将其数据设置为原始数据.然后,我想从editingRecord.original中获取数据及其键和值,并通过AJAX请求将其发送到服务器.

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.

好的,我找到了解决方案.

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.