1

I need to search for a keyword over an array of objects and replace all instances of it.

For example, I have the following array:

const test = [
  {
    marketType: 90,
    displayName: "FT Total Match {scoreType} Over / Under 0.75 Remove",
},
{
    marketType: 90,
    displayName: "FT Total Match {scoreType} Over / Under 1 Remove",
},
]

I want to find and replace all {scoreType} with goals in the array above.

So far I have tried converting the array to a string, running a replace on it, and converting it back to an array. But when I console log the result, I still see {scoreType} and no errors.

console.log('result: ', JSON.parse(JSON.stringify(test).replace('{scoreType}', 'goals')));

Can anyone tell me what I've done wrong?

0

5 Answers 5

2

Just try with map:

const result = test.map(item => ({
  ...item,
  displayName: item.displayName.replace('{scoreType}', 'goals'),
}))
Sign up to request clarification or add additional context in comments.

Comments

1

You can use spread and Array#map to do something like this perhaps:

const test = [
  {
    marketType: 90,
    displayName: "FT Total Match {scoreType} Over / Under 0.75 Remove",
},
{
    marketType: 90,
    displayName: "FT Total Match {scoreType} Over / Under 1 Remove",
},
]

newTest = test.map(obj => ({...obj, displayName: obj.displayName.replace('{scoreType}', 'goals')}))
console.log(newTest);

Comments

1

Converting an object to string and then working on it is a very vague approach and may lead to undesired bugs.

You may loop over the array using Array#forEach, and replace the text of displayName by using a regular expression, generated out of the source string.

const test = [{
    marketType: 90,
    displayName: "FT Total Match {scoreType} Over / Under 0.75 Remove",
  },
  {
    marketType: 90,
    displayName: "FT Total Match {scoreType} Over / Under 1 Remove",
  },
];

const search = 'scoreType';
const replacement = 'goal';

test.forEach(item => {
  const regex = new RegExp(`\{${search}\}`, 'g')
  item.displayName = item.displayName.replace(regex, replacement);
});

console.log(test);

Comments

0

Use map to iterate and replace displayName like this.

var updatedTest = test.map(obj => ({...obj, displayName: obj.displayName.replace('{scoreType}', 'goals')}));

Comments

0

To fix your original code, you would have to use a global regular expression replace:

const test = [
  {
    marketType: 90,
    displayName: "FT Total Match {scoreType} Over / Under 0.75 Remove",
},
{
    marketType: 90,
    displayName: "FT Total Match {scoreType} Over / Under 1 Remove",
},
]

console.log('result: ', JSON.parse(JSON.stringify(test).replace(/{scoreType}/g, 'goals')));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.