Updating a string in JavaScript by dynamically adding values from a JSON object

In my current function, I am making a request to fetch data and storing it as an object (OBJ).

Afterwards, I make another request to get a new URL that requires me to update the URL with values from the stored data.

The information saved in the object is as follows:

{
  "location": {
    "ip": "78.152.221.20",
    "success": true,
    "type": "IPv4",
    "continent": "Europe",
    "continent_code": "EU",
    "country": "Ireland",
    "country_code": "IE",
    "country_flag": "https://cdn.ipwhois.io/flags/ie.svg",
    "country_capital": "Dublin",
    "country_phone": "+353",
    "country_neighbours": "GB",
    "region": "County Dublin",
    "city": "Swords",
    "latitude": "53.4557467",
    "longitude": "-6.2197406",
    "asn": "AS15502",
    "org": "Vodafone Ireland",
    "isp": "Vodafone Ireland Limited",
    "timezone": "Europe/Dublin",
    "timezone_name": "Greenwich Mean Time",
    "timezone_dstOffset": "0",
    "timezone_gmtOffset": "0",
    "timezone_gmt": "GMT 0:00",
    "currency": "Euro",
    "currency_code": "EUR",
    "currency_symbol": "€",
    "currency_rates": "0.926884",
    "currency_plural": "euros",
    "completed_requests": 49
  }
}

The second request provides this URL which needs to be updated accordingly:

"url": "https://api.sunrise-sunset.org/json?lat={{ location.latitude }}&lng={{ location.longitude }}"

I attempted to create a function that manipulates the string and returns it. Once returned, it should be set as a string template literal like so:

`https://api.sunrise-sunset.org/json?lat=${OBJ['location']['latitude']&lng=${OBJ['location']['longitude']`

Unfortunately, this approach is not working as expected. The string is being used without taking into account the previously stored values in OBJ.

Below is the code snippet for reference. Any suggestions, pointers, or feedback would be greatly appreciated.

const interpolateURLorMessage = (string) => {
  if (CONST.DEBUG) {
    console.log('functions.checkURLorMessage: string:', string);
  }

  if (!string) {
    return null;
  }

  if (string.includes('{{') && string.includes('}}')) {
    const myRegexp = /\{{(.*?)\}}/g;
    const matches = string.match(myRegexp);

    let newURL = `${string}`;
    matches.forEach((ele) => {
      const match = ele;
      let newMatch = ele.replace('.', '\'][\'');
      newMatch = newMatch.replace('{{', '${OBJ[\'');
      newMatch = newMatch.replace('}}', '\']');
      newMatch = newMatch.replace(/\s/g, '');
      newURL = newURL.replace(match, newMatch);
    });

    return newURL;
  } else {
    // Noting to interpolate
    return string;
  }
};

Answer №1

A simplistic approach is taken in this implementation, utilizing a replacer function with regex and split(.) to assume that values within brackets are property values. For more intricate scenarios, consider employing eval or more sophisticated parsing techniques. Lodash offers property path accessing functions which could save you from having to develop them from scratch.
Mustache templates are another viable option, and they can be precompiled to minimize overhead.

However, for the straightforward use case at hand, this solution should suffice.

var OBJECT={};CONSTANTS={DEBUG:true};

const interpolateData = (string) => {
  if (CONSTANTS.DEBUG) {
    console.log('functions.checkData: string:', string);
  }

  if (!string) {
    return null;
  }

  if (string.includes('{{') && string.includes('}}')) {
    return string.replace(/\{{(.*?)\}}/g,(result,param1)=>param1.trim().split('.').reduce((acc,piece)=>acc[piece],OBJECT));
  } else {
    // No interpolation required
    return string;
  }
};

var urlObject = {"url": "https://api.sunrise-sunset.org/json?lat={{ location.latitude }}&lng={{ location.longitude }}"};

var details = {
  "location": {
    "ip": "78.152.221.20",
    "success": true,
    "type": "IPv4",
    "country": "Ireland",
    "city": "Dublin",
    "latitude": "53.4557467",
    "longitude": "-6.2197406",
    "currency": "Euro"
  }
};

OBJECT=details;
console.log(
interpolateData(urlObject.url)
);

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

"Upon loading the page, I encounter JavaScript errors related to Angular's ngOnInit function. However, despite these errors,

I have a page in angular where I am loading data in the ngOnInit function. The data loads correctly and is displayed on the page, everything seems to be working fine. However, I am encountering numerous javascript errors in the console stating cannot read ...

Automate populating input fields with data

I need help with a form that has four input boxes. Is it possible to automatically fill the remaining three input boxes with the value entered in the first box when the user clicks a button using JavaScript? Or should I aim to prefill the textboxes with ...

Obtaining cookies from a separate domain using PHP and JavaScript

Imagine you have a cookie set on first.com, called "user". Now, the goal is to retrieve that cookie on second.com using JavaScript and AJAX. Unfortunately, it's not working as expected and you're receiving xmlHttp.status=0. Here is a sample code ...

XMLHTTP communication issue between JavaScript and Node.js

I have a request from an HTML page to a Node service. The service functions perfectly in Firefox and Chrome when accessed through the URL. It also works flawlessly when I use curl and Postman. However, when using XMLhttpsRequest, it triggers an error eve ...

What steps can be taken to resolve the issue of receiving the error message "Invalid 'code' in request" from Discord OAuth2?

I'm in the process of developing an authentication application, but I keep encountering the error message Invalid "code" in request when attempting to obtain a refresh token from the code provided by Discord. Below is a snippet of my reques ...

Implementing Ionic 4 with HTML2Canvas technology

Looking for a way to convert HTML into an image within an Ionic 4 application. I attempted to use html2canvas, however, it was unsuccessful and displayed the following message in the console: Below is the code snippet I used: var element = document.getEl ...

Mastering the art of invoking a JavaScript function from a GridView Selected Index Changed event

In my current setup where I have a User Control within an Aspx Page and using Master Page, there's a GridView in the User Control. My goal is to trigger a javascript function when the "Select" linkbutton on the Gridview is clicked. Initially, I succe ...

Using Yii2, create a button with an onclick event that executes a JsExpression

I need to submit a form with an array of elements whose number is unknown. class DynamicForm extends Model { /** var string[] */ public elements[]; } In the view where the form submission takes place, I want to include a button that triggers a Ja ...

Authenticate yourself as a user or an organization on mongodb

I am currently developing an application that requires user registration and login, as well as organization registration and login. I have implemented the use of Node.js Passport with a local strategy for authentication. While I have successfully created t ...

I just finished crafting a dynamic line chart with d3.js within a React environment. However, I am now looking to add some personalized touches to enhance its appearance. Could you kindly review the details and code

I want to create a line chart using React and D3, similar to the one depicted in this image. Presently, I have partially implemented the chart with the code provided below. You can see it here. The code snippet I've developed so far is outlined as f ...

Failed to set Firebase data: The first argument provided contains an undefined property

When it comes to creating an event, here's my approach: export const handleEventCreation = ({ title, time, location }) => { const newEventKey = firebase.database().ref('/events').push().key; const updates = {}; const eventDetails ...

Implementing Keycloak Policies to Secure a Node.js API

Hello everyone, this is my first time reaching out for help here so please bear with me if I miss out on any important information or make some mistakes. Apologies in advance for the lengthy text. Summary of My Objective (I might have misunderstood some ...

Selenium javascript troubleshooting: encountering problems with splitting strings

Hello, I am new to using selenium and encountering an issue with splitting a string. <tr> <td>storeEval</td> <td>dList = '${StaffAdminEmail}'.split('@'); </td> <td>dsplit1 </td> < ...

Guide to converting a JSON string into an array of strings within a DataFrame

Recently delving into Scala, I've spent a solid 3 hours grappling with how to successfully parse a basic JSON string into an array of strings within a dataframe. Below is the code snippet causing me trouble: import spark.implicits._ import org.apach ...

Tips for populating Google Heatmap LatLng using a Java ArrayList in JSP

When a user enters dates on a JSP page, the latitude and longitude values are stored in a Java ArrayList. This is the servlet with the ArrayList: String startDate=request.getParameter("from"); String endDate=request.getParameter("to"); List<LocInfo> ...

Creating an AI adversary for a simple Tic Tac Toe game board: a step-by-step guide

Being new to programming, I recently completed a basic Tic Tac Toe gameboard successfully. However, as I progress to the next phase of my assignment which involves implementing an AI opponent, I encountered several challenges. As a novice in programming, ...

What is the trick to getting an accordion to expand when hovering, rather than when clicking?

Can the accordion be set to expand when hovering instead of clicking? Also, how can a different action be triggered on click? LATEST I was specifically referring to using the jQuery UI accordion widget for this functionality. ...

Obtaining npm packages with dependencies to GitHub projects through Nexus OSS proxy can be achieved by following these steps

Our team operates in a closed-off network that lacks internet access. We recently made the decision to implement Nexus OSS for utilizing npm, Maven, and other dependency management systems. However, upon setting the npm registry URL to the Nexus proxy UR ...

Accessing Ionic rootScope within the config stateprovider - A step-by-step guide

Is it possible to access the value of $rootScope in the following line? .config(function($stateProvider, $urlRouterProvider) { $stateProvider // I am trying to retrieve the value of $rootScope here. } ...

Retrieve information from a JSON script using C#

I need to extract data from a homepage, but the information I'm looking for is embedded in a JSON script. How can I retrieve this value? For example: <div id="contentWrap"> <div id="contentTextWrap"> <div id="contentText ...