[英]Convert array of strings to array of objects
Try to use array.prototype.map to ease your work, 尝试使用array.prototype.map来简化您的工作,
var newArray = arr.map(function(str){
return JSON.parse("{" + str.substring(0,str.length - 1).replace(/lat/,'"lat"').replace(/lng/,'"lng"') + "}")
});
As well as, if you have the string in that array in a proper format, then some unnecessary .replace()
can be removed which will results in performance boost. 同样,如果您以适当的格式在该数组中包含字符串,则可以删除一些不必要的
.replace()
,这将导致性能提升。
You can do this: 你可以这样做:
<!DOCTYPE html>
<html>
<body>
<script>
var data = ["lat: 0, lng: 0;", "lat: 25.233, lng:22.455;"];
var newData = new Array();
for(var i = 0; i < data.length; i++)
{
var temp = data[i].replace(/lat/g, "\"lat\"");
temp = temp.replace(/lng/g, "\"lng\"");
temp = temp.replace(/;/g, "");
temp = "{" + temp + "}";
newData.push(JSON.parse(temp));
}
console.log(newData);
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.