Getting rid of quotes in a JSON result

My unique code snippet

Retrieve data = Array[2] : 
                 0:object 
                     id : "1"  lat : "76.23" long:"21.92" 
                 1:object 
                     id:"2" lat:"10.23" long:"12.92"

var newCoords=[];

for(_i = 0; _i < retrieve_data.length; _i++)
{

     var tmp = retrieve_data[_i];
     var coordinates = [retrieve_data[_i]['lat'], retrieve_data[_i]['long']];
     newCoords[tmp.id] = JSON.stringify(coordinates);
 }
 console.log(newCoords);

The result stored in newCoords is -

 [1: "["76.2350","21.9253"]", 3: "["10.5650","21.3653"]", 6: "["60.5650","55.3653"]"]

this represents a JSON string

However, I am looking to format it as follows - {"1": [76.235,21.9253], "3": [10.565,21.3653], "6": [60.565,55.3653]}

Is there a solution to achieve this formatting?

Answer №1

Utilize the parseFloat method to convert strings to numbers,

var abc = new Object();
for(_i = 0; _i < swipe_data.length; _i++){
    var t1 = [parseFloat(swipe_data[_i]['latitude']), parseFloat(swipe_data[_i]['longitude'])];
    abc[tmp.id] = t1
}
console.log(JSON.stringify(abc));

Give this code a try, it should function correctly.

Please keep in mind:

  1. abc needs to be an Object, not an Array.
  2. Avoid using JSON.stringify when assigning values to keys.
  3. Only use JSON.stringify once all key values have been updated in your Object.

Answer №2

The perfect solution to this problem is as follows:

let newArray = [];

for(let i = 0; i < data.length; i++)
{
    let temp = data[i];
    let coordinates = [data[i]['latitude'], data[i]['longitude']];
    newArray[temp.id] = JSON.stringify(coordinates);
    newArray[temp.id] = newArray[temp.id].replace('"','');
}
console.log(newArray);

This code snippet effectively removes any quotation marks found in the string.

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

Identify the quantity of dynamically added <li> elements within the <ul> using jQuery

I'm facing an issue where I need to dynamically add a list of LI items to a UL using jQuery. However, when I try to alert the number of LI elements in this list, it only shows 0. I suspect that it's because the code is trying to count the origina ...

Passing arguments to an external function in jQuery from a dynamically loaded Ajax page

Despite its confusing title, the issue at hand is actually quite simple. My homepage contains a script that loads an external PHP file for a specific section of my website. Within this PHP file, I need to call a function from the main JavaScript file (th ...

Counting the number of key-value pairs for a specific key in a JSON data can be achieved by implementing

Is there a way to determine if __metadata and ItemToEkbeNav are the root elements for their children who have key-value pairs? I've attempted various methods such as Object.keys().length and Array.isArray(), but haven't been able to retrieve the ...

The Material-ui DatePicker seems to be malfunctioning and as a result, the entire form is not

Struggling to get my DateTimePicker component (could be DatePicker) working after following installation instructions from various sources. I've spent a day and a half attempting to make it functional without success. If you can help me create a separ ...

Finding the Ideal Location for Controllers in an Express.js Project

I'm relatively new to software development and one concept that I find challenging is organizing the directory structure of various projects. As I prepare to embark on an Express project, I prefer keeping controller classes separate from route callbac ...

Characteristics within the primary template element of a directive

I'm having an issue with the following directive code: .directive('myDirective', function () { restrict: 'E', replace: true, transclude: true, scope: { label: '@', ngModel: '=', ...

Windows encountering a Node npm error while searching for tools version

Currently, I am encountering an issue while trying to use node on my Windows 8.1 operating system. The problem arises when I attempt to install npm packages using 'npm install package.json'. It all started when I began using Redis, but I'm n ...

What is the reason behind VueJS animations only functioning in a single direction?

I'm completely baffled by this issue. It seems that Vue3 is able to apply the move animation class correctly for a <transition-group/> when there is a list of items, but this only happens if the list is moved forward. I've created a CodePen ...

Steps to Identifying Discrepancies in JSON Documents and Displaying the Line Number of Each Variation

I need to compare two JSON files that have the same order of objects. My goal is to identify and print out any differences between them, along with the line number where each difference occurs. For instance, The desired output is: "Discrepancy detected in ...

Count the occurrences of x.status being equal to 10 in AngularJS

I have 3 different statuses: 10, 20, and 30. I am trying to determine how many times x.status equals 10 and display that count. My initial approach was something like this: count="x.status" where="x.status == 10" Count: {{value}} <!DOCTYPE html> ...

Tips for navigating to an element with Nightwatch

I am currently using nightwatch for end-to-end testing of my application. One of the tests is failing because it seems unable to scroll to the element that needs to be tested. I am wondering if scrolling is necessary, or if there is another workaround. Her ...

What is the most effective way to organize an array according to a key function that is computationally intensive?

After posting this question regarding sorting an array with a key function, it became evident that utilizing a comparison function was inevitable. The challenge at hand includes: Having a resource-intensive key function that needs to be transformed into ...

Ways to prevent the repetition of keys associated with values

I am currently dealing with an array called serialNumbers, which can have different structures. For example: lot: 1 Serial: 2 lot: 1 Serial: 3 lot: 1 Serial: 4 ...or it could look like this: lot: 1 Serial: 5 lot: 1 Serial: 9 lot: 8 Serial: 2 lot: ...

Why does the UseEffect hook in next.js result in 2 fetch requests instead of the expected 1?

I am encountering an issue where my code is triggering two requests to my API using the GET endpoint. Unfortunately, my understanding of useEffect() is not deep enough to pinpoint where the problem lies. I want to avoid putting unnecessary strain on the ...

Is there a way to access the state value within the reducer function of createSlice?

Currently, I am utilizing redux-toolkit within my react project. A concern arises in a specific reducer inside the createSlice method where I aim to incorporate an existing array of entities from the state and then merge it with a new array before finalizi ...

Ways to automatically close the external window upon logging out in Angular 12

I have successfully created an external window in my Angular application. Everything is working as expected, but I am facing an issue when trying to automatically close the external window upon user logout. Although I have written the code below and it wo ...

Encountering an issue with Vuex action dispatch when using electron

I'm currently working on an Electron app with Vuex. The store is set up for the entire application using modules. One of my test modules is Browser.js: export default { namespaced: true, state: { currentPath: 'notSet' }, mutatio ...

Update MYSQL table values using AJAX and jQuery, then dynamically refresh the updated values on the web page

Hey there! I am fairly new to utilizing ajax and encountering some difficulty with a fundamental concept. In my MySQL table called "users," I have various user information stored, including the balance they pledge to donate. My goal is to create a div elem ...

How can we create external labels for a polar chart in ng2-charts and chart.js, with a set position outside the circular rings?

Currently, I am working on creating a polar chart using Angular along with chart.js version 2.8.0 and ng2-charts version 2.3.0. In my implementation, I have utilized the chartjs-plugin-datalabels to show labels within the polar chart rings. However, this p ...

Place JavaScript buttons within a form element without triggering form submission upon clicking the buttons

Struggling to find the right words, but I'll give it a shot. I have a PHP form with multiple fields, including a textarea where I store some PHP values. I wanted to enhance the appearance of the PHP values by adding a beautifier with CSS styling. Ever ...