Assign a specific function to every element within a collection of JSON entities

I have a scenario where my code retrieves a list of JavaScript objects as JSON via AJAX. These objects are then parsed using JSON.parse and stored in a variable.

var myListOfObjects = [ 
    {"id":1,"Name":"John","xcoord":23.7,"ycoord":37.2},
    {"id":2,"Name":"Mary","xcoord":17.7,"ycoord":54.6},
    ....
   ];

I'm trying to figure out the most efficient way to associate the same method with each of these objects, so that the method can be easily called during iteration:

myListOfObjects.forEach( function(person){
    console.log( person.getDistance() );
    } );

One approach could be to define the parameter within each iteration, but this doesn't seem to be the most efficient method. Also, implementing this with d3js might be challenging as it would require reiterating over the list before binding it to a DOM selection.

Any suggestions or insights would be greatly appreciated.

Answer №1

Develop a function getDistance(person) that is housed in a centralized location rather than within the person objects.

Answer №2

Per the recommendation by @dfsq in the comments, one option is to add some flair to my JSON objects:

function AdornedIndividual( requestData ){
    this.individual = requestData;
}

AdornedIndividual.prototype.calculateDistance = function(){
    return this.individual.xcoord*this.individual.xcoord + this.individual.ycoord*this.individual.ycoord;
    };

The data retrieved from ajax calls is then embellished within a loop.

myDataList.forEach( function(person){
    var adornedPerson = AdornedIndividual( person );
    console.log( adornedPerson.calculateDistance() );
    } );

Ultimately, enhancing the data could be carried out during the JSON.parse() stage by defining a reviver parameter.

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

How to create a vertically scrollable div within another div by utilizing scrollTop in jQuery

I need assistance with scrolling the #container div inside the .bloc_1_medias div. The height of #container is greater than that of .bloc_1_medias. My goal is to implement a function where clicking on the "next" and "previous" text will scroll the #contai ...

Issue with Submit Button Functionality following an Ajax Request

I am facing an issue where the submit button does not work after an ajax call, but works fine if I reload the page. The problem arises when a modal is displayed for email change confirmation. If the user confirms the change, the form submits successfully. ...

Guidance on Implementing Promises in Ionic 2 and Angular 2

Here are two functions that I need to implement: this.fetchQuizStorage(); this.retrieveQuizData(); fetchQuizStorage() { this.quizStorage.getAnswers().then(data => { return data; }); } retrieveQuizData() { this.quizData.getQuiz().t ...

Direct user to an external webpage with Vue 3

I created a navigation bar with links to external social media platforms. After clicking on the GitHub link, I encountered some errors and here are the URLs for reference: https://i.sstatic.net/KCh3C.png https://i.sstatic.net/OXQOK.png <template> ...

Using Ajax to make a request on the same page but specifically within a column

I'm currently experimenting with AJAX to display live CSV data on my website. Right now, the AJAX script triggers on button click, but what I really want is for the data to be shown in a grid view without requiring a refresh or clicking a button. Howe ...

The supertest request body cannot be found

Testing my express server POST endpoint using supertest has been a challenge for me. Although everything works perfectly in postman, I encountered an issue when trying to pass body parameters into the test. It seems like the body parameters are not being p ...

Angular developers are struggling to find a suitable alternative for the deprecated "enter" function in the drag and drop CDK with versions 10 and above

By mistake, I was working on an older version of Angular in StackBlitz (a code-pane platform). I came across a function called enter on GitHub, but it didn't solve my issue. I was working on a grid-based drag and drop feature that allows dragging bet ...

Is there a way to retrieve the current object as a JSON string from inside the object using either jquery or javascript?

Looking for a way to return the current instance as a JSON text so that the values can be sent via an ajax request to a server-side script. Uncertain about where to apply the "this" keyword in a jQuery selector function Actor(){ this.input=function(pnam ...

Encountering an error with TypeScript in combination with Angular 2 and Grunt. The error message is TS

Currently in my angular2 Project, I am utilizing grunt for automating the compilation of my typescript files. Everything seems to be working fine as my files are compiling, but I keep encountering errors: app/webapp/ng2/audit_logs/auditLogs.ts(2,3): erro ...

Problem with using puppeteer to interact with a dropdown menu

I have a project in which I am utilizing puppeteer to create a bot that can automatically check for my college homework assignments. The problem I am encountering is that when the bot tries to click on a dropdown menu, it fails and I receive an error messa ...

Which is better: specifying a name in window.open() or using replace?

If the current window is www.myparent.com and a button labeled "a" is clicked, it triggers the following function window.open('children','same','',??). Subsequently, a new page will open as www.myparent.com/children. On the o ...

Guide on converting retrieved data from MySQL into JSON using PHP

I'm currently working on converting data retrieved from a MySQL database into JSON format using PHP. Below is the code snippet I am utilizing: try { $statement = $db->prepare($query); $result = $statement->execute($query_params); $ ...

Using JavaScript, swap out the default "item added to cart" message with a custom Sweet Alert notification in WooCommerce

After removing the standard "Added to cart" message provided by WooCommerce, I have implemented a new code snippet using Sweet Alert. The goal is to eliminate all default "added to cart" messages and exclusively use the Sweet Alert feature. Although my co ...

When making a POST request from the client-side JavaScript, the req.body is coming back as an empty

I have been encountering several questions related to the same topic, but unfortunately, none of them have resolved my issue. Hence, I am posting a new question here. My objective is to send a POST request from client-side javascript to the Backend using ...

Tips for loading a webpage directly to the center instead of the top position

Is there a way to make the page open at a specific div halfway down the page instead of starting from the top? Here is an example: <div id="d1"> <div id="d2"> <div id="d3"> <div id="d4"> <div id="d5"> <div id="d6"> Do ...

Generating aggregated statistics from JSON logs using Apache Spark

Recently delving into the world of Apache Spark, I've encountered a task involving the conversion of a JSON log into a flattened set of metrics. Essentially, transforming it into a simple CSV format. For instance: "orderId":1, "orderData": { ...

Experiencing an issue with the countdown timer while utilizing react-countdown library

Currently, I am in the process of creating a countdown timer that allows users to input time in minutes and start or stop the clock. However, I have encountered two challenges: I defined a state running to determine if the clock is running, and based on t ...

Tips for adjusting the border color of a MUI Select field

https://i.stack.imgur.com/rQOdg.png This MUI select box changes color from blue to black based on selection. The challenge is to customize the text and border color to white (currently set as blue). Any suggestions on how to achieve this? ...

Bringing in a variable from a React component to a JavaScript file

I've created a React component called Button with two states named name and players. Now, I need to access these states in a separate JavaScript file that is not a component. Below are the relevant code snippets: Button.js import {useState} from &qu ...

Reading multiple files in NodeJS can be done in a blocking manner, and then the

When retrieving a route, my aim is to gather all the necessary json files from a directory. The task at hand involves consolidating these json files into a single json object, where the key corresponds to the file name and the value represents the content ...