gpt4 book ai didi

javascript - 将多维数组转换为特定的字符串格式

转载 作者:行者123 更新时间:2023-11-30 14:05:24 27 4
gpt4 key购买 nike

我收到一个数组,我必须将其转换为特定的字符串格式。

这是数组:

formdata: [
1: {name: "gender", value: "F", focus: 0, type: "radio"}
2: {name: "firstname", value: "empty", focus: 0, type: "input"}
3: {name: "lastname", value: "empty", focus: 0, type: "input"}
4: {name: "birthday", value: "empty", focus: 0, type: "input"}
5: {name: "street", value: "empty", focus: 0, type: "input"}
6: {name: "streetNo", value: "empty", focus: 0, type: "input"}
]

这是它应该转换成的特定字符串格式:

let formdata = gender.radio|F|0;firstName.text|empty|1;lastName.text|empty|0;street.text|empty|0;houseNumber.text|empty|0;zip.text|empty|0;city.text|empty|0;country.select-one|de|0;birthdate-day.text|empty|0;birthdate-month.text|empty|0;birthdate-year.text|empty|0;email.email|empty|0;code.text|filled_out|0

我认为最好使用 JSON.stringify。我已经尝试了几种变体:

let formdata = JSON.stringify(
formdata: [
1: {name: "gender", value: "F", focus: 0, type: "radio"}
2: {name: "firstname", value: "empty", focus: 0, type: "text"}
3: {name: "lastname", value: "empty", focus: 0, type: "text"}
4: {name: "birthday", value: "empty", focus: 0, type: "text"}
5: {name: "street", value: "empty", focus: 0, type: "text"}
6: {name: "streetNo", value: "empty", focus: 0, type: "text"}
])
.replace(/(\]\]\,)\[/g, "]\n")..replace(/(\[\[|\]\]|\")/g,"");

它们都不起作用。

有什么解决办法吗?

谢谢!

最佳答案

我认为只需在数组上使用 map() 即可。并返回模板字符串。然后通过';'

join()数组

const formdata = [
{name: "gender", value: "F", focus: 0, type: "radio"},
{name: "firstname", value: "empty", focus: 0, type: "input"},
{name: "lastname", value: "empty", focus: 0, type: "input"},
{name: "birthday", value: "empty", focus: 0, type: "input"},
{name: "street", value: "empty", focus: 0, type: "input"},
{name: "streetNo", value: "empty", focus: 0, type: "input"},
]


let res = formdata.map(({name,value,focus,type}) => `${name}.${type}|${value}|${focus}`).join(';')

console.log(res)

关于javascript - 将多维数组转换为特定的字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55499736/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com