javascriptarrayobject

How to get key value pairs in array object in javascript


I have a array of json object and i am trying to get it as key value pair. This is the code

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);
      }
    });

Here in decodedcontent, there is a placeholder %Tenantid%, and i am trying to replace it with a correct id. nstead of a json object, the parameter is comng from a api response like this,

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

If it is a array object my code is not working.

How to get key and value from a array object. Like in key place "%tenantid%" , and in value the id "a5462b57-a249-4778"


Solution

  • Make a regular expression by joining the parameters keys, then .replace with a replacer function that looks up the value on the object using the matched key.

    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]
      )
    );