Replace values of an object based on Keys

Asked

Viewed 41 times

0

I have an object with settings that return from a server in the following format:

    {
      "example-url": "http://examples.com",
      "example2-url": "${example-url}/examples",
      "example3-url": "${example-url}/ex",
      "example4-url": "${example2-url}/teste"
    }

Wanted to replace the strings with their respective values contained inside the object, thus staying:

    {
      "example-url": "http://examples.com",
      "example2-url": "http://examples.com/examples",
      "example3-url": "http://examples.com/ex",
      "example4-url": "http://examples.com/examples/teste"
    }

How do I map the object and give replace ?

  • My first question is: Does the server really have to return this result? what is the reason behind this logic? can you change the server?

  • @Sergio Sim, the server needs to return the object in this format, as it is used in other applications. It was made this way because it is a Spring Cloud Config.

  • 1

    I assume you’re missing " in your initial object, both answers below took that assumption.

  • Corrected, @Sergio. Thanks for pointing.

1 answer

1


One way to do this is by using replace on Keys values using a loop for:

const obj = {
      "example-url": "http://examples.com",
      "example2-url": "${example-url}/examples",
      "example3-url": "${example-url}/ex",
      "example4-url": "${example2-url}/teste"
    }

for(let item in obj){
   // pega o que estiver dentro de ${} com regex
   let url = obj[item].match(/\${(.+?)}/);
   // faz o replace pelo valor da key se encontrou o padrão da regex acima
   if(url) obj[item] = obj[item].replace('${'+url[1]+'}', obj[url[1]]);
}
    
console.log(obj);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.