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 } ]
Updated on: 2020-11-23T10:06:07+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements