Rearranging a JSON Object post editing

Currently, I am working on a project where I need to display and sort a list of items based on a JSON object. This includes sorting by both string values and integers within the object.

So far, I have been successful in listing and sorting the items by string values and test integers like latitude. The sorting functionality is working correctly.

Below is the JSON code for parks:

[
    {
        "name": "Greenhead Park",
        "latitude": 53.648748,
        "longitude": -1.796985,
        "image": "Greenhead_Park.jpg"
    },
    {
        "name": "Shibden Park",
        "latitude": 53.730610,
        "longitude": -1.838229,
        "image": "Shibden_Park.jpg"
    },
    {
        "name": "Beaumont Park",
        "latitude": 53.625146,
        "longitude": -1.809171,
        "image": "Beaumont_Park.jpg"
    }
]

However, my current challenge is sorting the items by distance. Unfortunately, the JSON file does not include a 'distance' element in the items. To resolve this, I am utilizing the Google Maps API - Geocode to calculate the distance between the user's location and the park's location.

In a for loop, I am adding a new 'distance' element to each item:

parks[i]["distance"] = distance;

Despite successfully adding the distance to the object, when I attempt to reference it by console.logging(a.distance), it returns as undefined.

This issue arises after temporarily adding an element to each item in the JSON object. Although it appears defined when logging the object, referencing it results in 'undefined.'

If any suggestions or insights are available, your help would be greatly appreciated.

EDIT: For clarification, here is the function that sorts the object:

function sortParks(parks,sortMethod){
    parks.sort(function(a, b){

        console.log(parks);
        console.log(a.name);
        console.log(a.distance);
        if(sortMethod == "az") return (a.name > b.name) ? 1 : (a.name < b.name) ? -1 : 0;
        else if(sortMethod == "za") return (a.name < b.name) ? 1 : (a.name > b.name) ? -1 : 0;
        else if(sortMethod == "dc") return a.distance - b.distance;
        else if(sortMethod == "df") return b.distance - a.distance;
        else alert("There was an issue identifying the sort type");

    });
    return parks;

}

The problem pertains to 'distance' being undefined when console.logged. While 'name' displays properly, attempting to access 'distance' results in 'undefined.'

Answer №1

Check out this JavaScript calculation that doesn't rely on using Google's API:

const earthRadius = 6371000; // in meters
const latitude1Rad = lat1.toRadians();
const latitude2Rad = lat2.toRadians();
const latitudeDifferenceRad = (lat2 - lat1).toRadians();
const longitudeDifferenceRad = (lon2 - lon1).toRadians();

const halfChordLength = Math.sin(latitudeDifferenceRad / 2) * Math.sin(latitudeDifferenceRad / 2) + Math.cos(latitude1Rad) * Math.cos(latitude2Rad) * Math.sin(longitudeDifferenceRad / 2) * Math.sin(longitudeDifferenceRad / 2);

const result = 2 * Math.atan2(Math.sqrt(halfChordLength), Math.sqrt(1 - halfChordLength));

const distance = earthRadius * result;

Answer №2

Is your code structured like this?

for(let i = 0; i < parksArray.length; i++) {
  parksArray[i]["distance"] = calculateDistance(parksArray[i].latitude, parksArray[i].longitude, user.latitude, user.longitude);
}

It seems to be working correctly without any undefined elements. You can view a more detailed example here: https://jsfiddle.net/yhkzo95L/

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

There appears to be a problem with the json file or a json-compatible dictionary that is being

My code is designed for a simple sockets rock paper scissors game where requests are made to the server using a request based system. I have utilized json files to structure this process, including storing a blank json file of the request format. However, ...

Using AJAX, extract URL parameters and retrieve corresponding data from MySQL database

Looking to extract a parameter from a URL link that resembles the following: www.example.com/?v=12345 The goal is to utilize AJAX to query a MySQL database for relevant data. Below is the AJAX code snippet: $.ajax({ type:"POST", url:"ajax2.php", data ...

Using JavaScript to extract variables from parsed JSON data

Could someone please help me understand how to run this code smoothly without encountering any errors? var test = 'Something'; JSON.parse('{"xxx": test}'); I am inquiring about this because I have a JSON object containing variables th ...

The JSON.parse function encountered an Uncaught SyntaxError due to an unexpected token 'o

I'm struggling with this JSON data: const info = [{ "ID":1,"Name":"Test", "subitem": [ {"idenID":1,"Code":"254630"}, {"idenID":2,"Code":"4566"}, {"idenID":3,"Code":"4566"} ] }]; console.log(JSON.parse(info)); //U ...

An error has occurred due to a connection timeout with the net.Socket

I have been attempting to send text to my network printer using a tcp connection. function print(buf2){ var printer = new net.Socket(); printer.connect(printer_port, printer_name, function() { console.log('Connected'); printe ...

Difficulty encountered when trying to parse JSON using JArray.Parse

It seems like there is something obvious that I am overlooking here. After receiving a `json` response from a service, I format it in a way that allows me to work with it as a `JArray`. The formatting code I have leaves me with what appears to be necessa ...

Tips for avoiding json character encoding (such as double quotes and commas) in PHP

Currently working on a PHP project that involves using PHP Excel. I have developed a PHP class to read an Excel sheet and return a simple JSON string. This JSON string is then used to display data in a table on a web page. However, the JSON string cannot c ...

Converting an OpenRasta XML request to JSON for response

I have a simple application using OpenRasta framework with a Home resource containing a single string property called Title (taken from the OpenRasta community documentation example). I've configured both XML and JSON data contracts for this resource ...

Tips for handling errors in ajax calls with alternative promises

While working on an application that offers weather data based on user location coordinates, I created the code provided below (also accessible in this codepen http://codepen.io/PiotrBerebecki/pen/QNVEbP). The user's location information will be retr ...

Swapping out the main view for the partial view

Recently, I wrote some jQuery code to fetch data from an action by passing in a dashID. The expected result was to receive HTML containing the relevant information. Unfortunately, my jQuery script is not returning the desired data. Below is the JavaScript ...

Updating the route in Express.js/Node.js to redirect form submission from `/page` to `/page/<input>`.Is this fine for you

How can I redirect a user from /page to /page/:nickname in Express after they enter a nickname and click submit? This is my code: // app.js app.get("/page", (request, response) => { response.render("page"); }); app.get("/page/:nickname", (reques ...

How can I properly parse the date format "Mon Oct 07 00:00:00 EDT 2013" using C#?

Currently, I am encountering an issue when trying to convert a json message from a server into C# objects using the RestSharp Deserializer. The problem lies in one field that is not properly converting into a datetime: The string value of the problematic ...

Utilizing ES6 Proxy leads to the occurrence of an error message stating "this is not a function" whenever a function call

As I ventured into the depths of ES6 Proxies, attempting to be a crafty developer, I found myself entangled in their complexities. My goal was to intercept any get or set operation on a property from a class I had written and ensure that they were stored e ...

Navigating Three.js coordinate systems

While working with vectors in three.js, I noticed that the axes seem to be mixed up. It's confusing because Y is the vertical axis, but X and Z appear "mirrored" causing objects to only look right when viewed upside-down. How can this issue be resolv ...

Contrast in functionality between a pair of variables within a controller

Could you please clarify the distinction between two variables a1 and a2: app.controller("someCtrl",function(){ this.a1=somevalue; var a2=somevalue; }); Also, can you explain the lifespan of variable a2? ...

What is the difference in memory usage for JavaScript objects between Node.js and Chrome?

It's puzzling to me why the size of the heap is twice as large as expected. I meticulously constructed a binary tree with perfection. I suspect v8 recognizes that each node consists of 3 fields. function buildTree(depth) { if (depth === 0) return n ...

Error: Certain Prisma model mappings are not being generated

In my schema.prisma file, I have noticed that some models are not generating their @@map for use in the client. model ContentFilter { id Int @id @default(autoincrement()) blurriness Float? @default(0.3) adult ...

Utilize the data storage API within Next.js or directly in the user's

Struggling to store this ini file on either the server or client, any help would be greatly appreciated. Additionally, I would like to display the ini info in the browser so that clients can easily copy and paste the information. However, I seem to be fac ...

Modifying the status using retrieved JSON information

My goal is to retrieve data from an external API and use it to update the state of my app. Although I can see the data in the console, the state of my app remains unchanged when I try to run setState. class App extends Component { state={ jobs:[] ...

Utilizing NSURLConnection's Delegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [self.responseData setLength:0];(URL10) self.jsonData = [[NSMutableData alloc]init];(URL20) self.genderData = [[NSMutableData alloc]init];(URL30) } ...