Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter out items in array of objects based on item in property array in JavaScript

What is the best way to return items in an array of object if they contain a certain property in a property which is an array?

I have the following array of objects:

const menus = [
  {
    id: 1,
    title: 'English',
    locations: ['MENU', 'MENU_EN']
  },
  {
    id: 2,
    title: 'Spanish',
    locations: ['MENU', 'MENU_SP']
  },
  {
    id: 3,
    title: 'German',
    locations: ['MENU', 'MENU_DE']
  },  
  {
    id: 4,
    title: 'German and english',
    locations: ['MENU', 'MENU_EN', 'MENU_DE']
  },
]

As an example, I am looking for a way to return any items which have ‘MENU_EN’ in the locations property. So I need a function which will return the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const filteredMenus = [
  {
    id: 1,
    title: 'English',
    locations: ['MENU', 'MENU_EN']
  },  
  {
    id: 4,
    title: 'German and english',
    locations: ['MENU', 'MENU_EN', 'MENU_DE']
  },
]

>Solution :

You can filter menus array using Array.prototype.filter() by checking if locations property includes the desired MENU_EN with Array.prototype.includes():

Code:

const menus = [{id: 1,title: 'English',locations: ['MENU', 'MENU_EN']},{id: 2,title: 'Spanish',locations: ['MENU', 'MENU_SP']},{id: 3,title: 'German',locations: ['MENU', 'MENU_DE']},{id: 4,title: 'German and english',locations: ['MENU', 'MENU_EN', 'MENU_DE']},]

const filteredMenus = menus.filter(({ locations }) => locations.includes('MENU_EN'))

console.log(filteredMenus)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading