cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Replace parts of string with values from array of objects

jpsheff
New Contributor

I need to replace portions of a string with values from an array of objects:

Input String:

$string1 = 'SELECT * FROM TABLE A WHERE COL1 = #1 AND COL1 = #2;'

In the following example I need to replace #1 and #2 with their correlated value from the given_parameters array.

Array of replacement values:

{

    "given_parameters": [

        {

            "name": "#1",

            "value": "A"

        },

        {

            "name": "#2",

            "value": "B"

        },

        {

            "name": "#3",

            "value": "C"

        }

    ]

}

Additional Notes:

There could be n number of portions of a string that need to be replaced by a value from given_parameters (it could be 1, or it could be 20 portions that require replacement).

What I have tried:

I have tried the following, but the comparison in the arrow function is a mismatched data type as match() is returning an array:

$string1.replace(/\#(.*?)[\s]|\#(\w*?);/g,JSON.parse(_application_parameter_json).given_parameters.find(x => x.name == $string1.match(/\#(.*?)[\s]|\#(\w*?);/g))).value)

I think this can be down using the map() function, but I havenโ€™t figured it out yet.

Any suggestions or feedback is greatly appreciated.

Thanks!

1 REPLY 1

bojanvelevski
Valued Contributor

Hey @jpsheff,

This can be achieved by using the .reduce() function. After you transform the parameter to an object field, use the following expression:

$parameters.reduce((acc,curr)=> acc.replaceAll(curr.name,curr.value),$string1)

Hereโ€™s a pipeline with the exact samples you provided, that does the transformation:

Replace string values from Array_2022_02_22.slp (5.3 KB)

I would suggest not to pass the JSON object as a parameter, if possible.

Regards,
Bojan