如何从数组中过滤掉值
How to filter out values from array
我有一个如下所示的对象:{"m":["bad-1", "ok", "also-ok", "bad-2", "bad-3"]}
我只想保留 m
中不以 bad-
开头的值。
此解决方案使用正则表达式和 reduce
运算符:
reduce .[] as $item ([]; if ($item | test("^bad-")) then . else . + [$item] end)
我学到的东西:
reduce
运算符
- 您可以通过过滤器管道 'subitems'(在
$item | test("^bad")
之上)
- 在这种情况下,您还可以使用 startswith/1
- 您还可以使用 map/1、select/1 和 not/0
- 您可以使用 |=
就地更新 "m" 插槽
因此:
.m |= map( select( startswith("bad-") | not ))
产生:
{
"m": [
"ok",
"also-ok"
]
}
我有一个如下所示的对象:{"m":["bad-1", "ok", "also-ok", "bad-2", "bad-3"]}
我只想保留 m
中不以 bad-
开头的值。
此解决方案使用正则表达式和 reduce
运算符:
reduce .[] as $item ([]; if ($item | test("^bad-")) then . else . + [$item] end)
我学到的东西:
reduce
运算符- 您可以通过过滤器管道 'subitems'(在
$item | test("^bad")
之上)
- 在这种情况下,您还可以使用 startswith/1
- 您还可以使用 map/1、select/1 和 not/0
- 您可以使用 |= 就地更新 "m" 插槽
因此:
.m |= map( select( startswith("bad-") | not ))
产生:
{
"m": [
"ok",
"also-ok"
]
}