

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Filter nested object by keys using JavaScript
Suppose, we have an array of objects like this −
const arr = [{ 'title': 'Hey', 'foo': 2, 'bar': 3 }, { 'title': 'Sup', 'foo': 3, 'bar': 4 }, { 'title': 'Remove', 'foo': 3, 'bar': 4 }];
We are required to write a JavaScript function that takes in one such array as the first input and an array of string literals as the second input.
Our function should then prepare a new array that contains all those objects whose title property is partially or fully included in the second input array of literals.
Example
The code for this will be −
const arr = [{ 'title': 'Hey', 'foo': 2, 'bar': 3 }, { 'title': 'Sup', 'foo': 3, 'bar': 4 }, { 'title': 'Remove', 'foo': 3, 'bar': 4 }]; const filterTitles = ['He', 'Su']; const filterByTitle = (arr = [], titles = []) => { let res = []; res = arr.filter(obj => { const { title } = obj; return !!titles.find(el => title.includes(el)); }); return res; }; console.log(filterByTitle(arr, filterTitles));
Output
And the output in the console will be −
[ { title: 'Hey', foo: 2, bar: 3 }, { title: 'Sup', foo: 3, bar: 4 } ]
- Related Questions & Answers
- Recursively list nested object keys JavaScript
- Changing value of nested object keys in JavaScript
- How to convert square bracket object keys into nested object in JavaScript?
- Nested collection filter with JavaScript
- Fetching object keys using recursion in JavaScript
- How to remove an object using filter() in JavaScript?
- Sum of nested object values in Array using JavaScript
- Fetching JavaScript keys by their values - JavaScript
- Print JSON nested object in JavaScript?
- Using find() to search for nested keys in MongoDB?
- JavaScript filter array by multiple strings?
- JavaScript: replacing object keys with an array
- Update JavaScript object with another object, but only existing keys?
- Constructing a nested JSON object in JavaScript
- How to generate child keys by parent keys in array JavaScript?
Advertisements