简体   繁体   中英

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,

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.

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>

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.

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