javascript change string into an array of objects

let dataString = "{lat: -31.563910, lng: 147.154312};{lat: -33.718234, lng: 150.363181};{lat: -33.727111, lng: 150.371124}";
let dataArray = dataString.split(';');

Produces the following output:

let dataArray = [
    "{lat: -31.563910, lng: 147.154312}",
    "{lat: -33.718234, lng: 150.363181}",
    "{lat: -33.727111, lng: 150.371124}"
  ]

Attempted to utilize JSON.parse(dataArray); but encountered a SyntaxError

The desired array should resemble this format:

let dataArray = [
    {lat: -31.563910, lng: 147.154312},
    {lat: -33.718234, lng: 150.363181},
    {lat: -33.727111, lng: 150.371124}
  ]

Answer №1

Give this a shot

let newString = string
  .replace(/lat/g, '"lat"')
  .replace(/lng/g, '"lng"')
  .replace(/;/g, ',')
JSON.parse('[' + newString + ']')

Interested in how this functions?

  • replace is utilized to put quotes around keys
  • replace is applied to change semicolons into commas
  • Subsequently, the string is enclosed in [...] making it valid JSON

Additionally, as noted in the remarks, if the string was formatted as JSON correctly, parsing it would be a simpler solution. It might be beneficial to address the issue where the string is generated if you have the ability to do so.

Answer №2

You're on the right track. Make sure to apply the JSON.parse() function to each element in the array to convert it into a JavaScript value.

array[z] = JSON.parse(array[z]);

Note: Your JSON data may need some adjustments to be in the correct format.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing dynamic JavaScript values in URL parameters before sending

When it comes to online payments, I need to send parameters to a specific URL. The calculations on my website are done in JavaScript, but the online payment company requires PHP parameters like MD5 hashing. To address this, I attempted to create a hidden ...

Place attribute value directly under the border of an HTML element using a combination of JavaScript and CSS

I'm currently working on a JavaScript script to scan the DOM for elements that have a specific custom attribute called example-type. The goal is to apply CSS styling to draw a border around these elements and then display the value of the example-type ...

The transition effect of changing opacity from 0 to 1 is not functioning properly in Firefox

Having some trouble with this animation not working in Firefox. I'm triggering the animation using JavaScript after a delay like so: document.getElementById('my_id').style.webkitAnimationPlayState = "running"; I've also attempted: s ...

Adjusting the outline color of a Material UI Select component in outlined mode to a different color when the dropdown is activated (currently shown as blue)

Is there a way to change the outline color of Material-UI select component outlined variant correctly? I need help changing the default blue color to red, any assistance would be greatly appreciated Click here for an image reference Reference code snippe ...

What are some effective methods for incorporating large JSON data into a node.js script?

What is the best way to import a large JSON file (550MB) into a node.js script? I attempted: var json = require('./huge-data-set.json') The script was run with an increased --max-old-space-size parameter node --max-old-space-size=4096 diff.js ...

Get Onsen UI 2 up and running without the need for Angular

Is it possible to install Onsen UI 2 without Angular? I have tried following various guides from , but when attempting the JavaScript method (> npm install onsenui) I consistently encounter a ReferenceError: angular is not defined. How can I properly in ...

What's the reason behind the malfunction of this code on Chrome?

After recently installing Mobiscroll, I have been using the date scroller feature with the following code to manage the textbox. <script type="text/javascript"> $(function() { // create a datepicker with default settings $("#begi ...

Guidelines for utilizing React to select parameters in an Axios request

As a newcomer to ReactJs, I am working with a Product table on MySQL. I have successfully developed a dynamic table in the front-end using ReactJS along with MySQL and NodeJs on the backend. The dynamic table consists of four columns: Product, Quantity, Pr ...

receiving an object as the return value in AngularJS

To access locfrnd in the code snippet below, follow these steps: I have created an Array named PlaceCollection containing 2 elements. place locfrnd, which is an array While I was able to successfully access place, I encountered an error when trying to a ...

When using Mongoose and Socket.IO, an empty string will not be printed if the result is empty

I'm facing an issue with a filter I created using socket.io and mongoose. Specifically, I'm trying to display a message if there are no results returned when querying, but it seems to not be working as expected. Restaurant.find({ $text : { $sear ...

When modifying the state of an array within a component, certain values may be overwritten and lost in the process

Currently, I'm faced with the challenge of ensuring that a component displays a loading screen until all images have completed loading. This is necessary because there are approximately 25 images that must finish loading before the page can be display ...

Ways to send a POST variable to PHP without refreshing the webpage

Is there a way to pass a simple variable from a text-box on a different page to PHP without reloading it? I've been informed that Ajax is required for this task, but I'm unsure of how to go about implementing it. Can someone provide me with a sam ...

Automate the process of filling up and activating a bootstrap dropdown upon a click, and clearing it out when it is

Is there a method to reveal the dropdown content only upon clicking instead of displaying all content at once and increasing the lines of HTML code? Perhaps using an onclick attribute on the button and incorporating a function inside? var data = [{ " ...

Revolutionize Your App with React Native's Interactive Bottom Sheet Option

Hello there! I am trying to create a FlatList with multiple items, each of which should trigger a bottom-sheet when clicked. I want to make this dynamic but I'm encountering an error. TypeError: undefined is not an object (evaluating `_this[_reactNat ...

How to decode JSON data into a JavaScript array and retrieve specific values using index positioning

Upon receiving a json response via ajax, the code looks like this: echo json_encode($data); The corresponding ajax code is shown below: $.ajax({ url:"PaymentSlip/check", data:{val:val}, type: 'POST', succe ...

Is there a way to display points on each vertex of my geometry using React, three.js, and Three-React-fiber?

I'm trying to figure out how to utilize the pointsmaterial and points object within three-react-fiber. Currently, I have a custom geometry that I've imported from a .gltf file and I'm rendering it like this: <mesh castShadow recei ...

Dynamically including and deleting classes upon clicking using React

Looking for a solution to handle a list of links. The goal is to add a class called "is-active" when a link is clicked, while also removing any existing "is-active" classes from other links. Only one link should have the "is-active" class at a time. This ...

Refresh the current page with jQuery Mobile when it is clicked

I have a multi page template in jQuery Mobile. How can I refresh the current page when clicking on a hyperlink or button? I am using JQM version 1.4.5 Despite trying the code suggested in how to refresh(reload) page when click button in jQuery Mobile, it ...

Having trouble with Instafeed JS loading?

I am currently experimenting with instafeed.js, but I am encountering difficulties getting it to load on a basic bootstrap page. While everything else on my page loads successfully, this particular container remains empty without any Instagram code presen ...

"Encountering an unfamiliar authentication strategy while using NodeJS passport

I am currently developing a project using node.js with passport authentication. However, I am encountering the following error message: Error: "Unknown authentication strategy " Below is my code: LocalStrategy = require('passport-local').Strat ...