2

I have this array containing strings with geographical data. enter image description here

How can i turn it into an array of objects like this:

obj[0] = {lat:0, lng:0}
1
  • From where comes from this array? Cannot you change it server side? Commented Aug 13, 2015 at 17:21

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.