如何使用Lodash JavaScript过滤以多种条件(字符串和值数组)过滤收集
我正在尝试使用Lodash进行多种条件过滤一个集合,它可以与字符串一起使用,但是我想在位置的一部分中滤除ID数组,并以状态字符串。我试图将ID更改为ID的“位置”:{“ ID”:[“ 1”,“ 4”]},
,但它不起作用
const collection = [
{account: {id: "1", name: "a"}, location:{id: "1", name: "x"}, status: "ok"},
{account: {id: "2", name: "b"}, location:{id: "2", name: "x"}, status: "ok"},
{account: {id: "3", name: "c"}, location:{id: "4", name: "y"}, status: "failed"},
{account: {id: "4", name: "d"}, location:{id: "4", name: "y"}, status: "ok"},]
let filterByConditions = {
"location":{"id" :"1"},
"account":{ "id": "1"},
"status": "ok",
};
let results = _.filter(collection, filterByConditions);
I'm trying to filter a collection with multiple conditions using lodash, it works fine with strings, but I want to filter by an array of id's for the part of the locations and string for status. I have tried to change the id to array of id's "location":{"id" :["1","4"]},
but it doesn't work
const collection = [
{account: {id: "1", name: "a"}, location:{id: "1", name: "x"}, status: "ok"},
{account: {id: "2", name: "b"}, location:{id: "2", name: "x"}, status: "ok"},
{account: {id: "3", name: "c"}, location:{id: "4", name: "y"}, status: "failed"},
{account: {id: "4", name: "d"}, location:{id: "4", name: "y"}, status: "ok"},]
let filterByConditions = {
"location":{"id" :"1"},
"account":{ "id": "1"},
"status": "ok",
};
let results = _.filter(collection, filterByConditions);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看来您正在尝试使用 filter 使用“匹配”速记的方法。此速记不支持“或”条件;仅确切匹配。但是,您可以传递
_。Filter
方法a predicate ,它将起作用:It looks like you're trying to use the filter method with the "matches" shorthand. This shorthand doesn't support an "or" condition; only exact matches. However, you can pass the
_.filter
method a predicate instead, and it'll work: