Exploring the method to retrieve key value pairs within an array object using JavaScript

I have an array of JSON objects and I am trying to extract it as key-value pairs. Here is the code snippet:

var fs = require('fs');
var parameters =
    {
      'Tenantid': 'a62b57-a249-4778-9732',
      "packagecategoryname":"Azure AD"
    };
    var decodedContent = `export const msalConfig = {
        auth: {
          clientId: "%Tenantid%",
          authority: "https://login.microsoftonline.com/common",
          redirectUri: window.location.origin,
          postLogoutRedirectUri: window.location.origin,
        },
        cache: { cacheLocation: "localStorage", storeAuthStateInCookie: false };`
    Object.entries(parameters).forEach((element) => {
      const [key, value] = element;
      console.log(key,value);
      if (decodedContent.includes("%"+key+"%") === true) {
        console.log("coming inside if");
        var newContent = decodedContent.replace("%"+key+"%",value)
        console.log(newContent);
      }
    });

In the decoded content, there is a placeholder %Tenantid%, which I am trying to replace with the correct ID. Instead of a JSON object, the parameters are now coming from an API response, like this:

var parameters =[
    {
      'Tenantid': 'a5462b57-a249-4778',
      "packagecategoryname":"Azure AD"
    }
];

My code does not work when the parameters are in an array object.

How can I extract the key and value from an array object, like having the key as "%tenantid%" and the value as the ID "a5462b57-a249-4778"?

Answer №1

Combine the keys from the `parameters` array to create a regular expression, then use `.replace` with a function that replaces the matched key with the corresponding value from the object.

var parameters =[
    {
      'Tenantid': 'a5462b57-a249-4778',
      "packagecategoryname":"Azure AD"
    }
];
const parametersObj = parameters[0];
var decodedContent = `export const msalConfig = {
    auth: {
      clientId: "%Tenantid%",
      authority: "https://login.microsoftonline.com/common",
      redirectUri: window.location.origin,
      postLogoutRedirectUri: window.location.origin,
    },
    cache: { cacheLocation: "localStorage", storeAuthStateInCookie: false };`
const pattern = new RegExp(
  `%(${Object.keys(parametersObj).join('|')})%`, // escape characters if needed: https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
);
console.log(
  decodedContent.replace(
    pattern,
    (_, key) => parametersObj[key]
  )
);

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

Pulling a div from beneath numerous other divs

I have been attempting to create a test case for a web application we are developing and I am on the verge of finding a solution, but there is one final hurdle that has me puzzled... Our requirement is to enable div elements to be draggable (which is work ...

Using Javascript to initialize events based on a variable

This particular plugin is structured in the following way: (function($){ var defaults = { param1:null, param2:null }; var methods = { init:function(params) { var ...

What is the reason for the JavaScript TypeError (undefined) being triggered when this object is used within a function?

I have defined a new object like this: function node(){ this.tag = null; this.Tdata = []; this.Tchilds = []; } Now, I am trying to use this object in a function: function Validate(root /*Ass ...

Ajax is not able to trigger a POST request to a PHP form

My form is not posting for some unknown reason, despite everything else on my server functioning properly. Below is the code snippet in question: PHP <?php if(isset($_POST['field1']) && isset($_POST['field2'])) { $data ...

Enhance the functionality of AngularJS (Restangular) by encapsulating service methods with a

Initially, when using basic $http, I had this code snippet in a service: var fetchSomeData = function() { var deferred = $q.defer(); $timeout(function() { $http.get('...mylongurl', { headers: { 'Content-Type& ...

Step-by-step guide on duplicating a div a set number of times

I am looking to replicate the entire div multiple times (e.g., on an A4 paper, top left corner, top right corner, bottom left corner, and bottom right corner). <script language="javascript" type='text/javascript'> function updateD ...

Change a nested for-loop into an Observable that has been transformed using RxJS

Currently, the following function is operational, but I consider it a temporary solution as I'm extracting .value from a BehaviorSubject instead of maintaining it as an observable. Existing Code Snippet get ActiveBikeFilters(): any { const upd ...

Extract the URL parameter and eliminate all characters following the final forward slash

Here is the URL of my website: example http://mypage.com/en/?site=main. Following this is a combination of JavaScript and PHP code that parses the data on the site. I am now looking for a piece of code that can dynamically change the URL displayed in the ...

What is the best way to free up memory after receiving responseText in a continuous streaming request?

Utilizing xmlHTTPRequest to fetch data from a continuous motion JPEG data stream involves an interesting trick where responseText can populate data even before the request is completed, since it will never actually finish. However, I have encountered some ...

Exploring the power of tRPC for creating dynamic routes in NextJs

Recently, I embarked on a new project using the complete t3 stack (Nextjs, prisma, tailwind, tRPC), and encountered a minor hiccup. To provide some context, within my database, I have an "artists" table containing fields such as name, email, address, id, ...

What exactly does the dollar sign signify in plain JavaScript code?

While watching a tutorial on object literals in JavaScript, I noticed something interesting. The instructor demonstrated creating an object like this: var Facebook = { name: 'Facebook', ceo: { firstName: "Mark", favColor: ...

When using a file uploader to set an image on v-model in Vue JS, it sometimes results in

I am currently using Vue JS 2 to develop an image uploader functionality. The input in question has a change function that triggers a function and sets the selected file to the v-model property. After logging the data, I noticed that only an empty object ...

What steps can I take to enhance the efficiency of this JavaScript DOM data manipulation algorithm?

Purpose I am working with a DOM that contains around 70 elements (divs with content). I have the need to move and toggle the display of these divs frequently and rapidly. Speed is crucial in this process. The trigger for moving and toggling these divs is ...

Save Scope in JSON format

Currently, I am developing a web application that dynamically displays specific prompts based on the field in focus. There are several different texts stored as scripts that I want to showcase at these different points. My goal is to incorporate scope dat ...

What is the best way to display an image and text side by side within a single row in react-table?

I am trying to display an image and text side by side within a single column in a React table. I have successfully added two texts together in a single column using the code below: Header: "Name", id: "User", accessor: (d) => ...

Evaluate One Input Value to Determine Another Input Value

Hey there, I've made an update to the fiddle but let me clarify what I'm trying to achieve. My goal is not to implement form validation as I already have that covered with the HTML5 "required" attribute. What I'm aiming for is to customize t ...

Reverse a filter within an ng-repeat loop - AngularJS

I have a question that I haven't found the answer to yet. Here is the issue I'm facing: The JSON data I am working with has this structure: [{ "batch_queue_name": "Batch One", "start_date": "12/01/2016 10:18 P.M.", "end_date": "12/03/2016 ...

Utilize AngularJS to Access Global JavaScript Variables

I recently encountered a situation where I needed to incorporate some dynamic functionality into a website I was building. This led me to AngularJS, which I decided to integrate into certain parts of the site rather than the entire thing. Within my JavaSc ...

Exploring the potential of Oracle Openscript in combination with Javascript using AngularJS,

I have encountered an issue while using Openscript on a form page with a clickable "save" button implemented as a div. Manually clicking the button triggers a javascript event that saves any changes made on the page. However, when I run the script, the but ...

Filtering with AngularJS based on integer comparison will assist in stream

Currently, I have implemented a "price" field on my website using the JQuery-UI slider. This field comprises of two integer values: minPrice and maxPrice. Suppose I possess an array of objects structured in this manner: objarr=[ { 'name'=&ap ...