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);
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:
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 filterByPredicate = (elem) => {
return elem.status === "ok" &&
elem.location.id === "1" &&
(elem.account.id === "1" || elem.account.id === "4");
};
let results = _.filter(collection, filterByPredicate);