0

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:

const filteredMenus = [
  {
    id: 1,
    title: 'English',
    locations: ['MENU', 'MENU_EN']
  },  
  {
    id: 4,
    title: 'German and english',
    locations: ['MENU', 'MENU_EN', 'MENU_DE']
  },
]
Ruben Kretek
  • 55
  • 1
  • 8
  • 2
    There are many different ways to achieve this. Please add the code _you've_ attempted to your question as a [mcve]. – Andy May 04 '22 at 08:20
  • 2
    [Filtering array of objects based on properties](https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes), [Checking if an array contains a value](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-a-value-in-javascript). – T.J. Crowder May 04 '22 at 08:22

1 Answers1

2

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)
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46