How to extract nested array from an object using JavaScript and Express

Upon examination of the object below:

[
  {
    id: 5fc0be2990a8a12cc0ba0b5c,
    projectName: 'E-271120-B',
    projectManagaer: '5f7f1ba973ff621da4322248',
    dataInici: 2020-11-26T23:00:00.000Z,
    dataEntrega: 2020-11-26T23:00:00.000Z,
    dtoGlobal: null,
    dtoProjecte: null,
    archived: false,
    created: 2020-11-27T08:51:57.242Z,
    updated: 2021-01-25T10:01:18.733Z
    tabs: [{permissionsUserID:[250,8]},{permissionsUserID:[3]}],
    __v: 3
  },
  {
    tabs: [{permissionsUserID:[3,350]},{permissionsUserID:[15]}],
    _id: 5fc0be4690a8a12cc0ba0b5f,
    projectManagaer: '5f7f0e69b5862e1a085db388',
    projectName: 'E-271120-C',
    dataInici: 2020-11-27T23:00:00.000Z,
    dataEntrega: 2020-11-29T23:00:00.000Z,
    dtoGlobal: null,
    dtoProjecte: null,
    archived: false,
    created: 2020-01-21T08:46:41.958Z,
    updated: 2021-01-21T08:46:41.958Z,
    __v: 2
  },
  {
    tabs: [{permissionsUserID:[31,350]},{permissionsUserID:[8,893]}],
    _id: 5fc0be4690a8a12cc0ba0b5f,
    projectManagaer: '5f7f0e69b5862e1a085db388',
    projectName: 'E-23410-C',
    dataInici: 2020-11-27T23:00:00.000Z,
    dataEntrega: 2020-11-29T23:00:00.000Z,
    dtoGlobal: null,
    dtoProjecte: null,
    archived: false,
    created: 2020-01-21T08:46:41.958Z,
    updated: 2021-01-21T08:46:41.958Z,
    __v: 2
  }
]

Each entry signifies a Project which consists of multiple tabs.

The goal is to fetch projects where at least one tab contains the ID of the currently logged-in user in permissionsUserID.

For instance, if the logged-in user possesses the ID 8, the desired projects are as follows:

[
  {
    id: 5fc0be2990a8a12cc0ba0b5c,
    projectName: 'E-271120-B',
    projectManagaer: '5f7f1ba973ff621da4322248',
    dataInici: 2020-11-26T23:00:00.000Z,
    dataEntrega: 2020-11-26T23:00:00.000Z,
    dtoGlobal: null,
    dtoProjecte: null,
    archived: false,
    created: 2020-11-27T08:51:57.242Z,
    updated: 2021-01-25T10:01:18.733Z
    tabs: [{permissionsUserID:[250,8]},{permissionsUserID:[3]}],
    __v: 3
  },
{
    tabs: [{permissionsUserID:[31,350]},{permissionsUserID:[8,893]}],
    _id: 5fc0be4690a8a12cc0ba0b5f,
    projectManagaer: '5f7f0e69b5862e1a085db388',
    projectName: 'E-23410-C',
    dataInici: 2020-11-27T23:00:00.000Z,
    dataEntrega: 2020-11-29T23:00:00.000Z,
    dtoGlobal: null,
    dtoProjecte: null,
    archived: false,
    created: 2020-01-21T08:46:41.958Z,
    updated: 2021-01-21T08:46:41.958Z,
    __v: 2
  }
]

This is the filtering mechanism applied:

async getAll(pagination, user) {
    try {
      const filter = {};
      if(pagination.archived) {
        filter['archived'] = pagination.archived;
      }
      if(pagination.search) {
        filter['$text'] = {$search: pagination.search}
      }

      const { Project: projectSchema } = this.getSchemas();
    

      const projectsDocs = await projectSchema.paginate(filter, {
        limit: pagination.limit ? parseInt(pagination.limit) : 10,
        page: pagination.page ? parseInt(pagination.page) + 1 : 1
      });

      if (!projectsDocs) {
        throw new errors.NotFound('No Projects.');
      }

      projectsDocs.docs.forEach(element => {
        element.tabs.filter( d => d.permissionsUserID.every( c => c.includes(user._id)));
      });

      return projectsDocs;
    } catch (error) {
      throw error;
    }
},

Answer №1

Here's a possible solution

const data = [...];
const userId = 10;
const filteredData = data.filter((item) => {
    const {categories} = item;
    let userFound = false;
    
    categories.forEach((category) => {
        if (category.users.includes(userId)) {
            userFound = true;
            return true;
        }
    });
    
    return userFound;
});

Answer №2

If you're looking to filter a list of projects based on user id permissions, this function is just what you need.

The Filter() method will return only the projects that match the specified criteria. By utilizing the Some() and Includes() methods in combination, you can accurately retrieve the subset of projects that meet your requirements.

const data = [
        /* project list */
    ],
    userId = 8;

function getProjectsForUserId (data, userId) {
    return data.filter((project) => {
        return project.tabs.some((tab) => {
            return tab.permissionsUserID.includes(userId);
        });
    });
}

console.log(getProjectsForUserId(data, 8));

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

Getting two integers and a string from MySql using Json

Looking for assistance with handling JSON data in a specific Android Class. Currently, the code retrieves only one object and the method is unclear on how to properly return it. The Protected Void method contains a setText function where the single JSON ob ...

Tips for selecting a JSON data node on-the-fly using jQuery

This is an example of my ajax function: $.ajax({ type: "GET", dataType: "json", async: false, url: "/wp-content/comment_data.php", data: 'songid=' + $array, success: function(data){ oTable.find('td').eac ...

Inside the function() in angular 2, the value of 'this' is not defined

I've integrated a UIkit confirmation modal into my app. However, I'm encountering an issue when trying to click the <button> for confirmation. The this inside the function is showing up as undefined. Here's the snippet of code in quest ...

SequelizeDatabaseError: Unselected database error encountered

I'm currently utilizing sequelize within my Express.js application, connected to a MySQL database. All of the necessary database credentials are securely stored in a .env file and have been verified to be accurate: DATABASE_NAME= mydb DATABASE_USERN ...

Verifying the status following a promise execution in the initial promise function

Below is the function I am currently working with: startGame = () => { this.buildDeck() .then(this.shuffleDeck) .then(this.dealToPlayer) .then(setTimeout(this.dealToPlayer, 2000)) .then(setTimeout(this.dealToDealer, 4000)) } In ...

Combining arrays in Javascript that share the same key by utilizing a loop

Can you advise on the most effective method to restructure an array for desired output? My goal is to combine all key values, whether in arrays or not, into objects with the same name key. Here is my current array: brands: [ 0:ZARA: {product: "ZARA Blac ...

Opting for a GET request over a POST request when interacting with a JSON RPC API

Can I send a GET request to a JSON RPC API? I'm attempting to do this with the random.org api (). It currently works with a POST request, but I need to use GET requests for all the APIs in my project. Below is the working POST request: function getNe ...

Retrieving data from an Ajax request

I am struggling with extracting the HP and PCP Payment fields from the JSON string obtained through a Jquery Ajax request: function DoPaymentSearch() { var start,end; start=Date.now(); var getQuotesSuccess = function(results){ end=Date.now(); alert(JSON.s ...

Tips for utilizing javascript to reset the heightline of the preceding keyword during a keyword search

Using JavaScript, I have implemented a search keyword function that highlights specific words in a paragraph. However, I am facing an issue. Currently, when searching for the next keyword, the previously highlighted text remains in red instead of reverting ...

Creating an array like this in JavaScript during an API call using Ajax

"WorkingHours": { "Monday" : { "open" : "10:00 am", "close" :"5:00 pm" }, "Wednesday" : { "open" : "10:00 am", "close" :"5:00 pm" ...

Is NodeJS primarily used as a socket library for network communication?

Here is a server program written in C language using socket functionality provided by libC # include <unistd.h> # include <sys/socket.h> # include <sys/types.h> # include <string.h> #include <netinet/in.h> main(){ int listfd ...

Collecting data from Jitsi

After setting up a Jitsi server using packages, I am now trying to log connection statistics to a database. Specifically, I want to store data about significant bitrate changes during video calls. Although I have some familiarity with JavaScript and WebRT ...

Transforming JSON data into comma-delimited values (with thousands separators) using Angular 5 and ES6 syntax

Is there a more elegant method to convert a JSON response into comma-separated numbers for displaying currency purposes? Here is the code I have currently: let data = { "business":{ "trasactionTableData":[ { ...

Trouble with fill() function

Check out this JavaScript code snippet I wrote: function Show(output, startX, startY){ var c = document.getElementById("myCanvas"); var context = c.getContext("2d"); context.arc(startX, startY, 3, 0, Math.PI*2, true); context.fill( ...

Is it possible to utilize AND (&&) OR ( || ) operators within the dependency array of React JS?

Is it possible to include the && and/or || operators in the dependency array like this: const isVisible = true const isModified = false useEffect(() => console.log("both are true"), [isVisible && isModified]) Some may consider this to ...

Issue with AngularJS: Copying and appending with $compile is not functioning properly

Below is the snippet of my angularjs Controller var $tr = angular.element("#parent" + obj.field_id).find("tbody"), $nlast = $tr.find("tr:last"), $clone = angular.copy($nlast); $clone.find(':text').val('' ...

Automatically format text fields to display time in hh:mm format from right to left as you type

Is there a way to automatically format hh:mm as the user types in a text field? The default format is 00:00, and I would like it to fill the minutes part when the first two characters are entered, followed by filling the hour part with the third and four ...

Enabling the option to follow a link once the script has completed execution

Is there a way to make the second link clickable only after a specific function has executed successfully? I have an EJS template with two links inside paragraphs. When the first link ("Run python") is clicked, a script is activated that takes some time to ...

Show the MySQL query results in a pop-up alert box

I need assistance with querying a MySQL database for certain results using PHP and then displaying the result in an alert dialog box through JavaScript. I am able to connect to the database, query the data successfully, and display it on a PHP page. Howeve ...

Handling 401 Status Codes with Access and Refresh Tokens in a React and Node Application

Dealing with a 401 status request from my server when the access token is expired is proving to be a challenge. I have implemented accessTokenVerify on the server side: require('dotenv').config(); const jwt = require("jsonwebtoken") ...