Jose the hose
Jose the hose

Reputation: 1895

Find and replace part of a property value in an array of objects

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?

Upvotes: 1

Views: 1778

Answers (5)

31piy
31piy

Reputation: 23859

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);

Upvotes: 1

Niladri Basu
Niladri Basu

Reputation: 10614

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);

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370809

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')));

Upvotes: 0

hsz
hsz

Reputation: 152226

Just try with map:

const result = test.map(item => ({
  ...item,
  displayName: item.displayName.replace('{scoreType}', 'goals'),
}))

Upvotes: 2

Amit Chauhan
Amit Chauhan

Reputation: 6879

Use map to iterate and replace displayName like this.

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

Upvotes: 0

Related Questions