简体   繁体   English

将字符串数组转换为对象数组

[英]Convert array of strings to array of objects

I have this array containing strings with geographical data. 我有这个包含地理数据字符串的数组。 在此输入图像描述

How can i turn it into an array of objects like this: 我怎样才能把它变成像这样的对象数组:

obj[0] = {lat:0, lng:0}

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() ,这将导致性能提升。

DEMO DEMO

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM