Search code examples
javascriptjavascript-objects

How do i loop through these objects inside an array using forEach?


I have an array and inside i have a group of objects and how would i loop through them and to make a check for which one of the objects have a status as true?

menuItems: [
  {
    text1: 'Apple',
    status: false,
    subItems: []
  },
  {
    text2: 'Orange',
    status: false,
    subItems: []
  },
  {
   text3: 'Banana',
    status: true,
    subItems: []
  }
]

I tried something like this:-

if(menuItems.forEach(active) === 'false') {
then('do something!!!')
}

Solution

  • An example:

    const menuItems = [
      {
        text: 'Apple',
        status: false,
        subItems: []
      },
      {
        text: 'Orange',
        status: false,
        subItems: []
      },
      {
       text: 'Banana',
        status: true,
        subItems: []
      }
    ];
    
    menuItems.forEach(menuItem => { if(menuItem.status) { console.log(menuItem.text) } });

    Read MDN!

    https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach