Jquery: 将字符串字典数组转换为数组
Jquery: Convert string dictionary array into array
我的数据是这样来的:
time_slot = "[{\"id\": \"3\",\"table\": \"Table 1\",\"time\": \"10:00-11:00},
{\"id\": \"4\",\"table\": \"Table 1\",\"time\": \"02:00-03:00\"},
{\"id\": \"8\",\"table\": \"Table 2\",\"time\": \"10:00-11:00\"},
{\"id\": \"10\",\"table\": \"Table 2\",\"time\": \"02:00-03:00\"}]"
我想要这样的结果:
[{id:3,table:"Table 1",time:"10:00-11:00"},
{id:4,table:"Table 2",time:"02:00-03:00},
.....
]
我正在尝试使用它来转换它们。
我从这里试过 :
let arr = time_slot.replace('{','').replace('}','').replace('[','').replace(']','').split(',')
arr.map((each)=>{let newVal = each.split('='); return {key: newVal[0], value: newVal[1]}})
但没有得到想要的结果。
time
值似乎缺少结束引号 "
。如果这只是一个错字,你可以简单地转换
JSON.parse(time_slot).map(r => ({...r, id: +r.id}))
您必须修复 json 并将字符串 ID 转换为数字
time_slot=time_slot.replaceAll("},{","\"},{").replace("}]","\"}]");
var times=JSON.parse(time_slot);
times.forEach(item => {
item.id=parseInt(item.id);
});
console.log(times);
结果
[{"id":3,"table":"Table 1","time":"10:00-11:00"},
{"id":4,"table":"Table 1","time":"02:00-03:00"},
{"id":8,"table":"Table 2","time":"10:00-11:00"},
{"id":10,"table":"Table 2","time":"02:00-03:00"}]
我的数据是这样来的:
time_slot = "[{\"id\": \"3\",\"table\": \"Table 1\",\"time\": \"10:00-11:00},
{\"id\": \"4\",\"table\": \"Table 1\",\"time\": \"02:00-03:00\"},
{\"id\": \"8\",\"table\": \"Table 2\",\"time\": \"10:00-11:00\"},
{\"id\": \"10\",\"table\": \"Table 2\",\"time\": \"02:00-03:00\"}]"
我想要这样的结果:
[{id:3,table:"Table 1",time:"10:00-11:00"},
{id:4,table:"Table 2",time:"02:00-03:00},
.....
]
我正在尝试使用它来转换它们。
我从这里试过
let arr = time_slot.replace('{','').replace('}','').replace('[','').replace(']','').split(',')
arr.map((each)=>{let newVal = each.split('='); return {key: newVal[0], value: newVal[1]}})
但没有得到想要的结果。
time
值似乎缺少结束引号 "
。如果这只是一个错字,你可以简单地转换
JSON.parse(time_slot).map(r => ({...r, id: +r.id}))
您必须修复 json 并将字符串 ID 转换为数字
time_slot=time_slot.replaceAll("},{","\"},{").replace("}]","\"}]");
var times=JSON.parse(time_slot);
times.forEach(item => {
item.id=parseInt(item.id);
});
console.log(times);
结果
[{"id":3,"table":"Table 1","time":"10:00-11:00"},
{"id":4,"table":"Table 1","time":"02:00-03:00"},
{"id":8,"table":"Table 2","time":"10:00-11:00"},
{"id":10,"table":"Table 2","time":"02:00-03:00"}]