我有这两个对象,并在开始和结束值
之间用双引号引起来。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, …}
我想要这个
0: {name:"0", type:"line", start: [20.600,37.4000], end: [28.2000,30.8000],...}
如何删除双引号,以便开始和结束值变为数字?
我尝试过:
0["start"].replace(/^"(.*)"$/, '$1');
=> typeof字符串
0["start"].slice(1, -1);
=> typeof字符串
Number(0["start"])
=>此返回NaN
我正在对我的NodeJs服务器进行Ajax发布调用,在那里JSON被转换为YAML文件,然后发送回去。
这是结果:
segments:
-
name: "0"
type: "line"
start: "[20.6000,37.4000]"
end: "[28.2000,30.8000]"
vel: 0.3
ang: 0
有效的Yaml,但我需要开始和结束值为数字
答案 0 :(得分:2)
使用JSON.parse,Array#map和spread operator的解决方案。不更改原始数据集。
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);
正则表达式解决方案:
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);
答案 1 :(得分:0)
您可以尝试使用JSON.parse
循环浏览文件并使用
JSON.parse(x['start']) // JSON.parse(0['start'])
答案 2 :(得分:0)
仅循环-请注意,转换时,小数点末将丢失零:
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)