从数组中查找特定字符串

Find certain strings from an array

我正在尝试对负载执行查找功能。

假设我有:

["john","abe","john","doe","peter"]

预期输出是

[
"john",
"john",
"peter"
]

我试过了

["john","abe","john","doe","peter"] find "john" or "peter"

但是没用。

我不知道怎么做。

您可以使用 filter() 函数来查找符合条件的项目。作为条件,您可以拥有另一个您感兴趣的元素数组,并测试当前元素是否包含在感兴趣的数组中。由于对输出没有明确的期望,所以我选择 return 所有匹配的元素。您可能想要 return 一些不同的东西。

%dw 2.0
output application/json
var choices=["john","peter"]
---
["john","abe","john","doe","peter"] filter ( choices contains $ )

输出:

[
  "john",
  "john",
  "peter"
]

匹配可以找到需要的字符匹配:

%dw 2.0
output application/json
var ip = ['john','abe','john','doe','peter']
var toFind = /john|peter/
---
flatten(ip map ($ match toFind))

输出:

[
  "john",
  "john",
  "peter"
]