Filter a JavaScript array of object another JavaScript array of objects

Neil Merton :

I have the following made-up JavaScript array of objects:

const permissions = [
  {
    moduleEnabled: true,
    moduleId: 1,
    moduleName: 'Directory'
  },
  {
    moduleEnabled: true,
    moduleId: 2,
    moduleName: 'Time off'
  },
  {
    moduleEnabled: false,
    moduleId: 3,
    moduleName: 'Tasks'
  },
  {
    moduleEnabled: false,
    moduleId: 4,
    moduleName: 'Documents'
  }
]

I also have the following array of objects based on a collection of widgets that are available to be displayed:

const widgets = [
  {
    id: 1,
    moduleId: 2,
    title: 'Your time off'
  },
  {
    id: 2,
    moduleId: 1,
    title: 'Your colleagues'
  },
  {
    id: 3,
    moduleId: 3,
    title: 'Your tasks'
  },
  {
    id: 4,
    moduleId: 5,
    title: 'Your sales pipeline'
  },
  {
    id: 5,
    moduleId: 4,
    title: 'Your documents'
  },
  {
    id: 6,
    moduleId: 6,
    title: 'Your legal cases'
  }
]

What I'd like to do is to reduce the array of objects widgets to a new array of objects filteredWidgets based on the values in the permissions array of objects, these being whether the moduleId is found, and also where the moduleEnabled is true.

I've tried the code below, but it's not working:

const filteredWidgets = []
for (const permission in permissions) {
  const found = widgets.filter((item) => item.moduleId === permission.moduleId && permission.moduleEnabled)
  if (found) {
    filteredWidgets.push(found)
  }
}
console.log('filteredWidgets\n', filteredWidgets)

Any help will be greatly appreciated. Thanks in advance.

Edit: include expected output:

const filteredWidgets = [
  {
    id: 1,
    moduleId: 2,
    title: 'Your time off'
  },
  {
    id: 2,
    moduleId: 1,
    title: 'Your colleagues'
  }
]
Mike D Sutton :

In your filter function, check for any permission which matches the given criteria:

const filteredWidgets = widgets.filter(widget =>
    permissions.find(permission =>
        (permission.moduleId === widget.moduleId) && permission.moduleEnabled));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=302365&siteId=1