Sort through an array containing JavaScript objects in order to filter out certain elements that match a different

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'
  }
]

Answer №1

Within your filter method, verify if there are any permissions that meet the specified conditions:

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

Answer №2

If you utilize the combination of .reduce() and .find(), you can achieve the desired outcome using the following code:

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' }];
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'}]

const result = widgets.reduce((a, c) => {
  const found = permissions.find(e => e.moduleId === c.moduleId)
  return found && found.moduleEnabled ? a.concat(c) : a;
}, []);

console.log(result);

I trust this solution will meet your needs!

Answer №3

If you have a list of permissions for certain modules, you can filter objects by their moduleId.

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' }],
    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' }],
    allowed = permissions.reduce((o, { moduleEnabled, moduleId }) =>
        ({ ...o, [moduleId]: moduleEnabled }), {}),
    filteredWidgets = widgets.filter(({ moduleId }) => allowed[moduleId]);

console.log(filteredWidgets);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №4

One approach involves using the reduce method to solve this problem.

To begin, you'll need to set up a Map and leverage it to create an Object with Object.fromEntries(). After that, proceed with utilizing the reduce function as outlined below.

const permissions = [
  {
    moduleEnabled: true,
    moduleId: 1,
    moduleName: 'Directory'
  },
  // Additional permission objects...
]

const widgets = [
  {
    id: 1,
    moduleId: 2,
    title: 'Your time off'
  },
  // Additional widget objects...
]

const permissonsMap = permissions.map((child,index) => {
  return [child.moduleId, {...child}]
})

const permissionsObj = Object.fromEntries(permissonsMap);

//console.log(permissionsObj);

const filteredWidgets = widgets.reduce((aggArr,currItem) => {
  if (permissionsObj[currItem.moduleId] && permissionsObj[currItem.moduleId].moduleEnabled){
    aggArr.push(currItem);
  }
  return aggArr;
},[])

console.log(filteredWidgets);

The key steps to focus on are:

const permissonsMap = permissions.map((child,index) => {
  return [child.moduleId, {...child}]
})

const permissionsObj = Object.fromEntries(permissonsMap);

//console.log(permissionsObj);

const filteredWidgets = widgets.reduce((aggArr,currItem) => {
  if (permissionsObj[currItem.moduleId] && permissionsObj[currItem.moduleId].moduleEnabled){
    aggArr.push(currItem);
  }
  return aggArr;
},[])

console.log(filteredWidgets);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Optimizing Java Performance by Using Method Invocation

In the process of developing a method to discover intersections within provided arrays. During my iteration of both sets of arrays, I pondered incorporating if(arr2.length > arr1.length){ intersection(arr2, arr1); } This concept arose from my de ...

The component contains a render method, however, it does not inherit from React.Component

A component is displaying a render method, however it does not extend React.Component. This may lead to potential errors. Please modify <Test> to extend React.Component instead. When utilizing the extends-classes library, it results in a react compo ...

Restricting array elements through union types in TypeScript

Imagine a scenario where we have an event type defined as follows: interface Event { type: 'a' | 'b' | 'c'; value: string; } interface App { elements: Event[]; } Now, consider the following code snippet: const app: App ...

Issue with socket malfunctioning when integrated with express

I’m encountering an issue with the socket in my program. While I can easily broadcast from any part of the program using "io" connection, I face limitations when trying to use "socket" for broadcasting unless it is within the same connection as "io." I a ...

Creating or updating JSON files using Node.js

I am currently working with JSON files that contain an array of objects. I am looking to update one of these objects and subsequently update the JSON file by overwriting the old file. I understand that this cannot be achieved using AngularJS, but rather wi ...

Meteor chat platform now offers the option to create multiple chat rooms

I've been working on an application that features multiple chat rooms. Currently, one of the rooms is functional in terms of sending and receiving messages. However, when I navigate to a different room and try to send a message, the message doesn&apos ...

Determine the value of a specific element within a deeply nested array

I understand that this question may have been asked multiple times before, but I am encountering an error when trying to use the following code: echo $result["tracks"]["title"]; An issue arises with a fatal error: 'Cannot use object of type stdCl ...

unable to gather information from suppliers

I'm currently building a login page with nextjs and spotify js, but I've run into the following error https://i.sstatic.net/cKiM8.png Here is the code snippet that is causing the issue: import React from 'react' import { getProviders ...

Dynamic starting point iteration in javascript

I'm currently working on a logic that involves looping and logging custom starting point indexes based on specific conditions. For instance, if the current index is not 0, the count will increment. Here is a sample array data: const data = [ { ...

Sending PHP variable to xmlhttp.responseText

I haven't come across this specific situation before, so I thought I would ask for help. My JavaScript code is using AJAX to call a PHP file, run the script in it, and then return a concatenated PHP variable via xmlhttp.responseText to alert that resp ...

Download function in Express.JS failing to retrieve file

I have been working on a Node.JS server using Express to generate and download PDFs based on user input. Previously, I used the <form action=""> method to call my API, but switched to Axios due to Netlify not supporting NuxtAPI. The program ...

What is the process for creating a folder using Firebase Cloud Functions with Storage?

How do I create a folder named "posts"? Storage bucket path --> gs://app.appspot.com/posts Code to generate thumbnail from storage object exports.generateThumbnail = functions.storage.object() .onChange(event => { const object = event.data ...

The hexagons configuration for tsParticles is experiencing technical difficulties

I'm struggling to implement the tsParticles library (specifically using react-tsparticles) in combination with the latest version of Next.js. However, when I try to use the particle.json file and bind it to the <Particles/> component, the partic ...

Sorting items using jQuery filter

I am working with two sortable div containers that are connected using connectWith. Both containers contain draggable items that can be moved as desired. These items have specific classes such as group1 and group2. Let's refer to the containers as con ...

Control the start and stop of an Express.js app in Node.js using PHP

I'm currently developing a web service using express.js in the node.js npm environment. In order to deliver this project to my client, I need to create a controller file that allows me to start and stop the server without having to use the command pr ...

Utilizing key values to access an array and generate a list of items in React.js

This marks my initiation on Stack Overflow, and I extend an apology in advance for any lack of clarity in my explanation due to unfamiliarity with the platform. My current task involves creating a resume with a dynamic worklist feature on my website. The ...

Utilize Vue.js and express.js to distribute HTML files securely

Currently, my tech stack includes Vue.js for the frontend and Express.js for the backend. When I kick off the express.js server using npm start, my goal is to serve the Vue frontend component. By utilizing the Vue generator and Express generator, I attemp ...

Tips for customizing the font color in Material UI Typography

Is it possible to change the color of only this text to red? return <Typography style={{ color: 'red' }}>Login Invalid</Typography> I came across this online solution, but I am unsure how to implement it as there is no theme={color ...

Loop through each JSON object and insert it into an HTML element

I am working on looping through a JSON object and converting it into HTML. While I can iterate through all the objects in the JSON, I am having trouble extracting just the first object. var res = '[{"ID":"246","mobile":"samsung","feedback":"feedback ...

Building an array of objects using a foreach loop

i am struggling to create an array of objects from two input groups, each group consists of 3 inputs with data-side attributes set to left or right every input has a class named "elm" and a data-pos attribute set to a, b, or c <input class="elm-left elm ...