[英]Filter array with match regex only returning the first match (javascript)
我必須過濾一個字符串數組並將其映射到另一個數組中,問題是它只匹配第一個匹配項,而另一個字符串不匹配它,因為我已經在 regex101 上嘗試了 apttern 並且它有效。
我有一個名為“堆棧”的對象,其中包含多個變量,為簡單起見,我只寫了一個我感興趣的對象(stackName)。 “堆棧”對象:
[
{
"stackName": "cc-dev-euw1d-c-1"
},
{
"stackName": "ngi-prd-euw1b-c-3"
}
]
我制作了以下代碼,以便我可以過濾並將這個“堆棧”對象映射到另一個數組中,在開頭添加一個字符串“none”,然后使用正則表達式模式過濾它,該模式查看數字之前末尾的字母是否為' C':
this.oldstacks = ['none', ...stacks
.filter(stack => stack.stackName.match('c(?=-\d)'))
.map(stack => stack.stackName)];
例如,這些字符串應該匹配:
cc-dev-agw1d-c-1
dd-prd-agw1b-c-3
但是這些不匹配,因為它們在數字前沒有“c”:
dd-prd-agw1b-d-3
dd-prd-agw1b-r-3
我想將 stacks 對象過濾到 oldStacks 對象中,所以它只需要與模式匹配的字符串,但我似乎無法找出如何,因為這樣它只需要第一個匹配項,我想要堆棧的所有匹配項。
謝謝
問題是match采用正則表達式而不是字符串,並且您只能使用匹配而不是前瞻斷言。
const stacks = [{ "stackName": "cc-dev-euw1d-c-1" }, { "stackName": "ngi-prd-euw1b-c-3" } ]; const oldstacks = ['none', ...stacks .filter(stack => stack.stackName.match(/c-\d/)) .map(stack => stack.stackName) ]; console.log(oldstacks);
您也可以使用reduce,而不是先過濾然后映射:
const stacks = [{ "stackName": "cc-dev-euw1d-c-1" }, { "stackName": "ngi-prd-euw1b-c-3" } ]; const oldstacks = ['none', ...stacks .reduce((acc, curr) => { if (/c-\d/.test(curr.stackName)) acc.push((curr.stackName)) return acc; }, []) ]; console.log(oldstacks);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.