1

Suppose I have an array of objects that have

name: id: school: address:

I know how to filter by one category, such as

data.filter(data => data[name].includes("Lake"))

to get all the objects whose name includes the word Lake.

But is there a way to filter the data to get all object where any of the fields includes the word?

data.filter(data => data.includes("Lake"))

doesn't work, I already tried.

Thank you!

1
  • You might find this answer useful to your use case. Commented Jan 22, 2022 at 2:38

2 Answers 2

1
const arr = [
  { id: 1, name: "name_1", school: "school_1", address: "address_1" },
  { id: 2, name: "lake", school: "school_2", address: "address_2" },
  { id: 3, name: "name_3", school: "lake", address: "address_3" },
  { id: 4, name: "name_4", school: "school_4", address: "lake" }
];

const anyKeyFilter = item => obj => Object.values(obj).includes(item);

const filteredArr = arr.filter(anyKeyFilter("lake"));

console.log(filteredArr);

You may use trim() and .toLowerCase() if you need it.

Sign up to request clarification or add additional context in comments.

Comments

1

const arr = [
  { id: 1, name: "name_1", school: "school_1", address: "address_1" },
  { id: 2, name: "lake", school: "school_2", address: "address_2" },
  { id: 3, name: "name_3", school: "lake", address: "address_3" },
  { id: 4, name: "name_4", school: "school_4", address: "lake" }
];


const filteredArr = arr?.filter((data) => Object.values(data)?.includes('lake'));

console.log(filteredArr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.