I have these 2 Objects with the double quotes around start and end value
0: {name: "0", type: "line", start: "[20.6000,37.4000]", end: "[28.2000,30.8000]", vel: 0.3, …}
1: {name: "1", type: "line", start: "[53.3000,25.0000]", end: "[52.7000,35.3000]", vel: 0.3, …}
and I want to have this
0: {name:"0", type:"line", start: [20.600,37.4000], end: [28.2000,30.8000],...}
how can I remove the double quotes so start and end values become Number?
I tried:
0["start"].replace(/^"(.*)"$/, '$1');
=> typeof String
0["start"].slice(1, -1);
=> typeof String
Number(0["start"])
=> this return NaN
I am doing a Ajax post call to my NodeJs Server, where the JSON gets converted to a YAML File and then sent back.
this is the result:
segments:
-
name: "0"
type: "line"
start: "[20.6000,37.4000]"
end: "[28.2000,30.8000]"
vel: 0.3
ang: 0
a valid yaml but I need the start and end Value as Number
Solution using JSON.parse , Array#map and spread operator . Does not mutate original data set.
const data=[{name:"0",type:"line",start:"[20.6000,37.4000]",end:"[28.2000,30.8000]",vel:.3},{name:"1",type:"line",start:"[53.3000,25.0000]",end:"[52.7000,35.3000]",vel:.3}]; const res = data.map(({start, end,...rest})=>{ start = JSON.parse(start), end = JSON.parse(end); return {...rest, start, end}; }) console.log(res);
Regex solution:
const data=[{name:"0",type:"line",start:"[20.6000,37.4000]",end:"[28.2000,30.8000]",vel:.3},{name:"1",type:"line",start:"[53.3000,25.0000]",end:"[52.7000,35.3000]",vel:.3}]; function stringToArray(data){ return data.match(/\\d(\\.?[0-9])*/g).map(Number); } const res = data.map(({start, end,...rest})=>{ start = stringToArray(start); end = stringToArray(end); return {...rest, start, end}; }) console.log(res);
You can try using JSON.parse
loop over your file and use
JSON.parse(x['start']) // JSON.parse(0['start'])
Just loop - note you will lose the zeroes at the end of the decimals when converting:
var arr = [{name: "0", type: "line", start: "[20.6000,37.4000]", end: "[28.2000,30.8000]", vel: 0.3}, {name: "1", type: "line", start: "[53.3000,25.0000]", end: "[52.7000,35.3000]", vel: 0.3}] arr.forEach(function(entry) { entry.start = JSON.parse(entry.start); entry.end = JSON.parse(entry.end); }) console.log(arr)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.