Home > Back-end >  How to replace a substring value and take that substring to make an API call and replace with that d
How to replace a substring value and take that substring to make an API call and replace with that d

Time:11-15

I have an object: `

{
    "object": {
        "id": 1,
        "string": {
            "stringWithoutData":"there is no data here"
            "stringWithData": "this is a string with this {{data.extended.action}}",
        },
    }
} 

I have an API with output

{
    "data": {
        "extended": {
        "action": "new sub string value "
        }
    }
} 

I want the first object to be:

{
    "object": {
        "id": 1,
        "string": {
            "stringWithoutData":"there is no data here"
            "stringWithData": "this is a string with this new sub string value",
        },
    }
}

`

how do I access the "object" and check if the values which are starting with '{{' and ending with '}}' and if the value with this substring exists, I have to extract that value to make an api call and based on the response, replace with the data into the object.

I did try to parse through the object but never was able to extract it properly and check the api response object for data and replace that in place of {{data.extended.action}}

CodePudding user response:

You can use Array#reduce to access the object value, and recursively traverse the object and replace the strings.

// create a replacer function
function template(str, data) {
  // replace everything bracket
  return str.replace(/{{.*?}}/g, match => {
    // split input by "." (next object)
    const spl = match.slice(2, match.length - 2).split("."); // slice to remove "{{" and "}}"
    
    return spl.reduce((obj, cur) => obj[cur], data); // go from the beginning of the object
  });
}

// recursively go though
const replace = (input, response) => {
  for(let key in input) {
    if (typeof input[key] === "string")
      input[key] = template(input[key], response);

    if (typeof input[key] === "object") {
      replace(input[key], response); // go through nested objects
    }
  }
  return input;
}


const input = {
  "object": {
    "id": 1,
    "string": {
      "stringWithoutData": "there is no data here",
      "stringWithData": "this is a string with this {{data.extended.action}}",
    },
  }
};

const response = {
  "data": {
    "extended": {
      "action": "new sub string value "
    }
  }
};
console.log(replace(input, response));

CodePudding user response:

If the object always has the place holder {{data.extended.action}}

Then you could simply use String.replace method modify the string.

const newValue = object.string.stringWithData.replace('{{data.extended.action}}', 'my new text here')
object.string.stringWithData = newValue
  • Related