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

Why won't Vanilla JavaScript work with my Rails application?

Having trouble implementing a full screen menu, no Rails errors but not working when project is run. Error received: Cannot read property 'addEventListener' of null JS code snippet: (function() { var Menu = (function() { var burger = d ...

What is causing the "unable to resolve dependency tree" error when using ng new newApp?

Struggling with creating a new Angular app using the command ng new app-name? When running the command, you may encounter the following error in the command line. Installing packages (npm)...npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve depen ...

The escape character appears to be misunderstood, causing an error due to an invalid escape sequence

When using the following syntax: executeJSCommand("location.href='StatusDetails.php?CHLD=1\&JNum=1024&JTitle=';"); An error occurs displaying: Invalid Escape Sequence ...

Verify the ability to view a webpage

I am currently working on creating a method to check if data access is equal to next.data.access. Since it's an array, I cannot use the includes method. It would be enough for just one of the data access values in the array to return true. auth.guard ...

Incorporate another parameter into the current JSON data

I am currently facing the following scenario: Several servlets are setting the HttpServletResponse content-type to application/json. This is how I am outputting my JSON: out.write(new Gson().toJson(myObject)); where myObject is an object that structur ...

Javascript alert: forgetting to add ; before statement causes SyntaxError

Seeking to incorporate a post-it application into my django website using Javascript/JQuery. Came across a tutorial and attempted to add it to my script, but encountered a SyntaxError: SyntaxError: missing ; before statement post-it.js:2:19 Not be ...

Assign a variable to the result of ajax that remains unchanged until it is specifically invoked

I am currently working on the final part of my radio script, specifically focusing on the "last song" section. My goal is to retrieve a URL from an external PHP script, play the song, and once the song ends, I want to set a global variable equal to the cur ...

Is there a way to search through an array of object arrays in JavaScript for a specific key/value pair using lodash or any other function?

I am faced with a task involving an array of objects. Each object has a key that needs to be used to search through sets of arrays containing similar objects. The goal is to determine if all the arrays contain the same value for a specific key in my object ...

Tips for concealing the URL in the address bar while using `<a href>` links

I have a variety of documents saved in a folder within an ASP MVC 5 project. Instead of directly linking to the document with an HTML tag, I am utilizing the following ng-href: <a ng-href="~/download/document/{{vm.document}}"></a> By using th ...

The utilization of the Angular date pipe significantly impacts the way dates are

When I use the pipe date:'MM/dd/YYYY' to display the date 2022-01-01T00:00:00, it shows as 1/01/2021 instead of 1/01/2022. This issue only occurs with this specific date. Why does this happen? The value of pharmacyRestrictionDate is 2022-01-01T0 ...

Managing a substantial JSON object on an Android device: Tips and Tricks

Currently, I am working on creating an Android application that interacts with an ASP.NET WebService. The Webservice sends a JSON object to the app, which then parses the data and displays it on the screen. However, I have encountered an issue where the ...

Issue with memory leakage detected during compilation of Angular 12 application

My coworker and I are currently in the process of optimizing our Angular 12 application for our enterprise. The Issue: One major challenge we have encountered while developing our application is the continuous increase in memory usage each time the angul ...

Invoking a JavaScript function within a different JavaScript function

Is there a way to ensure that the JavaScript function works properly even when using a text editor? var editor = $('#CKEditor1').ckeditorGet(); editor.on("instanceReady", function () { this.document.on("keydown", function (event) { ...

The onClick functionality for the IconComponent (dropdown-arrow) in React Material UI is not functioning properly when selecting

I have encountered a problem in my code snippet. The issue arises when I attempt to open the Select component by clicking on IconComponent(dropdown-arrow). <Select IconComponent={() => ( <ExpandMore className="dropdown-arrow" /> )} ...

Prevent automatic page reload when the button is clicked

Currently, I am in the process of developing a system for internal use within our company that will enable our service desk team to unlock user accounts and reset passwords. I have successfully implemented the PHP/POST functions and integrated them with t ...

Encountering the error code 'ERR_EMPTY_RESPONSE' while utilizing an AJAX-powered live search feature

My website features a live AJAX search bar that retrieves records from a MySQL database. However, when users repeatedly conduct searches by modifying the search criteria, some web browsers display an error message stating 'ERR_EMPTY_RESPONSE'. ...

After submitting my form, the Bootstrap Modal does not hide as intended by my Ajax

I am facing an issue with my webpage that displays 6 Bootstrap Cards in 3 columns. Each card contains an image, name, description, and a footer button. When a user clicks on the button, a Bootstrap Modal opens with specific data fetched from a SQL row by I ...

Using Angular to invoke the transclude directive function inside the transcluded component

I am looking to develop a component that includes a transcluded section, take a look at this example: http://jsfiddle.net/vp2dnj65/1/ Upon clicking the "do" button in the example, nothing seems to happen. Is there a way to execute the transcluded cont ...

Angular list with a repeating group of radio buttons

I have a set of 'options', which consists of the following: {Id: 1, Label: "option 1"}, {Id: 2, Label: "option 2"} Additionally, I have a list of 'products' structured as follows: {Id: 1, Name: "Name 1", Recommend: options[0]}, {Id: ...

Angular5 causing all divs to have click events at once instead of individually triggered

I am a beginner when it comes to working with Angular and I have encountered an issue. I created a click event on a FAQ page in Angular 5, but the problem is that when I click on one FAQ, they all open up instead of just the targeted one. Here is my TypeS ...