将表单数据数组对象转换为 JSON [重复]

Posted

技术标签:

【中文标题】将表单数据数组对象转换为 JSON [重复]【英文标题】:Convert Form Data Array Object to JSON [duplicate] 【发布时间】:2021-05-26 20:40:07 【问题描述】:

我正在尝试将表单数据对象转换为 JSON

var dataFormItin = $("#formitinerary").serializeArray(); 

结果

itinerary: 
'itinerary[0][date]': undefined,
'itinerary[0][title]': 'Day 1 to Colombo',
'itinerary[0][destinationId]': '5ff3b8d7f0f3bf04b8141362',
'itinerary[0][program]': 'asd',
'itinerary[0][transfer_duration]': '2 hours'

我想让它像

itinerary : [
      date : ..., title :...,
      date : ..., title :...
]

【问题讨论】:

这能回答你的问题吗? Convert JS object to JSON string 【参考方案1】:

也许,它会解决你的问题

// 1. Example Data
const serializeArray = [
   name: "itinerary[0][date]", value: "" ,
   name: "itinerary[0][title]", value: "Day 1 to Colombo" ,
   name: "itinerary[0][destinationId]", value: "5ff3b8d7f0f3bf04b8141362" ,
   name: "itinerary[0][program]", value: "asd" ,
   name: "itinerary[1][date]", value: "" ,
   name: "itinerary[1][title]", value: "Day 1 to Colombo" ,
   name: "itinerary[1][destinationId]", value: "5ff3b8d7f0f3bf04b8141362" ,
   name: "itinerary[1][program]", value: "asd" ,
]

// 2. Define object key here
const arrayOfKey = ['date', 'title', 'destinationId', 'program']

// 3. Create empty array object
const arrayObject = []

// 4. Transform Serialize Array into Array Object
for(i = 0; i < serializeArray.length / arrayOfKey.length; i++ )
  const newObject = 
  for(const key of arrayOfKey)
    newObject[key] = (serializeArray.find(data => data.name == `itinerary[$i][$key]`)).value
  
  arrayObject.push(newObject)


// 5. Show the result
console.log(arrayObject)

/**
 * [
  
    date: '',
    title: 'Day 1 to Colombo',
    destinationId: '5ff3b8d7f0f3bf04b8141362',
    program: 'asd'
  ,
  
    date: '',
    title: 'Day 1 to Colombo',
    destinationId: '5ff3b8d7f0f3bf04b8141362',
    program: 'asd'
  
]
 */

【讨论】:

以上是关于将表单数据数组对象转换为 JSON [重复]的主要内容,如果未能解决你的问题,请参考以下文章

Javascript将数组转换为对象数组

怎样将json数据转换成匿名数组或者泛型对象(c#)

如何将数据实体转换为 JSON 字符串

php如何将json对象转字符串

laravel怎么把对象转换为数组

如何将数据实体转换为 JSON 字符串