Home > front end >  Jquery: Convert string dictionary array into array
Jquery: Convert string dictionary array into array

Time:05-25

My data is coming in this way:

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\"}]"

I want to have result like that:

[{id:3,table:"Table 1",time:"10:00-11:00"},
{id:4,table:"Table 2",time:"02:00-03:00},
.....
]

and i am trying to convert them by using this.

i tried this from here Converting Map<String,String> into array in jquery:

let arr = time_slot.replace('{','').replace('}','').replace('[','').replace(']','').split(',')
arr.map((each)=>{let newVal = each.split('='); return {key: newVal[0], value: newVal[1]}})

but not getting desire results.

CodePudding user response:

There seems to be a missing closing quote " for the time value. If that is just a typo you can simply convert

JSON.parse(time_slot).map(r => ({...r, id: parseInt(r.id)}))

CodePudding user response:

you have to fix your json and convert string Id to number

time_slot=time_slot.replaceAll("},{","\"},{").replace("}]","\"}]");
var times=JSON.parse(time_slot);
times.forEach(item => {
    item.id=parseInt(item.id);
});

console.log(times);

result

[{"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"}]
  • Related