Below is a fictional JavaScript array made up 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'
}
]
Additionally, there is another array of objects representing available widgets to display:
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'
}
]
The task at hand is to filter the widgets
array of objects down to a new array called filteredWidgets
based on specific criteria from the permissions
array. This involves matching the moduleId
and checking if the corresponding moduleEnabled
value is true
.
Although attempts have been made with the following code snippet, it has not yielded the desired outcome:
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)
Your assistance in achieving the expected output would be highly appreciated. Thank you in advance.
Edit: Expected output included below:
const filteredWidgets = [
{
id: 1,
moduleId: 2,
title: 'Your time off'
},
{
id: 2,
moduleId: 1,
title: 'Your colleagues'
}
]