簡體   English   中英

在對象數組中查找並替換部分屬性值

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

我需要在對象數組上搜索關鍵字並替換它的所有實例。

例如,我有以下數組:

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",
},
]

我想在上面的數組中找到所有{scoreType}並將其替換為goals

到目前為止,我已經嘗試將數組轉換為字符串,對其進行替換,然后將其轉換回數組。 但是,當我使用控制台記錄結果時,我仍然看到{scoreType}並且沒有錯誤。

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

誰能告訴我我做錯了什么?

只需嘗試使用map

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

您可以使用spreadArray#map進行以下操作:

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

將對象轉換為字符串然后對其進行處理是一種非常模糊的方法,並且可能導致不希望的錯誤。

您可以使用Array#forEach遍歷數組,並使用從源字符串生成的正則表達式替換displayName的文本。

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

使用map來迭代和替換displayName,就像這樣。

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

要修復原始代碼,您必須使用全局正則表達式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'))); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM