-1

I have an object which contains UTF-8 characters as strings - I figured I could make another object with the list of characters and how I'd like to replace them?

The Data Object

var data = [
  {"my_string":"ABC & I","value":13,"key":8},
  {"my_string":"A “B” C","value":12,"key":9}
 ];

The Replacement Object

var str_to_change = [
    {value: "&", replace: "&"},
    {value: "“", replace: ""},
    {value: "”", replace: ""}
];

I'd like to write a function where anytime a str_to_change.value is seen inside data.my_string, replace it with str_to_change.replace

Is this the best way to go about changing various character strings, and how would I execute this? I found this: Iterate through object literal and replace strings but it's a little more complex since I'm not just replacing with a singular string.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
MayaGans
  • 1,815
  • 9
  • 30

1 Answers1

3

Rather than an array of objects, consider constructing just a single object with multiple keys:

const replacements = {
  "&": "&",
  "“": '',
  "”": '',
};

Then, with the keys, escape characters with a special meaning in regular expressions, join the keys by |, construct a regular expression, and have a replacer function access the matched substring as a property of the replacements object:

var str_to_change = [{value: "&", replace: "&"},
{value: "“", replace: ""},
{value: "”", replace: ""}];
const replacements = Object.fromEntries(str_to_change.map(({ value, replace }) => [value, replace]));
const escape = s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
const pattern = new RegExp(Object.keys(replacements).map(escape).join('|'), 'gi');

var data = [{
  "my_string": "ABC & I",
  "value": 13,
  "key": 8
},
{
  "my_string": "A “B” C",
  "value": 12,
  "key": 9
}];

const mappedData = data.map(({ my_string, ...rest }) => ({
  ...rest,
  my_string: my_string.replace(
    pattern,
    prop => replacements[prop]
  )
}));
console.log(mappedData);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thanks so much! I love the idea of just matching the key value pairs for the strings I want to replace, this is great! – MayaGans Jan 25 '20 at 23:35