Home > Enterprise >  lodash filter match if property value contains "x"
lodash filter match if property value contains "x"

Time:11-04

If I have an array of objects like so:

const array = [
{name: "Jim", attributes: "strong, handsome, tall", age: 28},
{name: "Alice", attributes: "blonde, thin, tall", age: 26},
{name: "Bob", attributes: "lazy, small, thin", age: 32}
]

Is there a way to use _.filter(array) to create a new array with objects whereby a property contains a value. Something like _.filter(array, attributes.contains("tall")) would return desired result of:

[
{name: "Jim", attributes: "strong, handsome, tall", age: 28},
{name: "Alice", attributes: "blonde, thin, tall", age: 26}
]

CodePudding user response:

This can be done with the built-in filter and checking if the attributes of the person includes "tall".

const array = [
{name: "Jim", attributes: "strong, handsome, tall", age: 28},
{name: "Alice", attributes: "blonde, thin, tall", age: 26},
{name: "Bob", attributes: "lazy, small, thin", age: 32}
];

const tallPeople = array.filter(
  (person) => person.attributes.includes("tall")
);

console.log(tallPeople);

CodePudding user response:

You can do this vanilla JS.

try the filter method, but please note it is a shallow copy - so if you update the original array, your filter will be different also.

array.filter(el => el.attributes.includes('tall'))

This is possible because the String type has the includes method.

Updated to use includes instead of contains. both work.

  • Related