Forum Discussion

jpsheff's avatar
jpsheff
New Contributor
4 years ago

Replace parts of string with values from array of objects

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

  • Hey Y'all, thank. you so much for your responses. I made a discovery of something that I wasn't aware of before asking this question. When the CSV Parser detects an error, one of the fields that is outputted in the error view is $original.record. Now that I know about this field, I can leverage it to determine which errors need to be reported and which errors may be ignored. Initially I had wanted to handle my error condition before the CSV Parser, but now I can handle it just as effectively post CSV Parser.

    Again, thanks so much for your support. I really love this facility as I know I can always count on the community to help me solve any challenge.

  • bojanvelevski's avatar
    bojanvelevski
    Valued Contributor

    Hey alex_panganiban,

    You can trim the record to fit the headers, which will result in additional record with the hidden character as a value for the first column, in this case "employee_id".

     

    From here, use Filter snap to exclude the records that doesn't have a "first_name" for example:

    !$.hasPath('first_name')

    Let me know if this works for you.

    Regards,

    Bojan

     

  • alex_panganiban - you can also use the "When errors occur" property in the Views tab of the CSV Parser snap to ignore errors during parsing or even route bad records to an error view and handle them more gracefully.

    Hope this helps!