What is the best way to filter intricate JSON based on a condition nested within the JSON

Managing a collection of complex objects that require filtering based on multiple conditions

var myList= [
  {
    "UserId": 1,
    "UserDetails": {
      "Department": [
        {
          "Name": "dept1"
        }
      ],
      "Projects": [
        {
          "Name": "Project1"
        },
        {
          "Name": "Project2"
        }
      ]
    }
  },
  {
    "UserId": 2,
    "UserDetails": {
      "Department": [
        {
          "Name": "dept2"
        }
      ],
      "Projects": [
        {
          "Name": "Project3"
        },
        {
          "Name": "Project4"
        }
      ]
    }
  },
  {
    "UserId": 3,
    "UserDetails": {
      "Department": [
        {
          "Name": "dept3"
        }
      ],
      "Projects": [
        {
          "Name": "Project5"
        },
        {
          "Name": "Project6"
        }
      ]
    }
  }
]

I need to filter based on two criteria: when Department Name is "dept3" or if there is a project with the Name "Project3"

var filteredElements=this.myList.filter((x)=>x.UserDetails.filter((y)=>y.Department... ??

How can I implement code to handle these dual filtering conditions?

Answer №1

In order to meet the required condition:

  1. The user must be a part of department "dept3"

    user.UserDetails.Department.some(department => department.Name == "dept3")

  2. There should exist a project named "Project3"

    user.UserDetails.Projects.some(project => project.Name == "Project3")

Combining these conditions together,

var filteredResults = this.myList.filter(user => 
    user.UserDetails.Department.some(department => department.Name == "dept3") || 
    user.UserDetails.Projects.some(project => project.Name == "Project3"))

Answer №2

Filtering out elements from myList where UserDetails Department includes 'dept3' or Projects include 'Project3'

Answer №3

Do not attempt to use the filter function on UserDetails because it is an object, not an array.

Instead, utilize the find method on Department and Projects with an OR condition between them along with the specified criteria.

var myList= [
    {
      "UserId": 1,
      "UserDetails": {
        "Department": [
          {
            "Name": "dept1"
          }
        ],
        "Projects": [
          {
            "Name": "Project1"
          },
          {
            "Name": "Project2"
          }
        ]
      }
    },
    {
      "UserId": 2,
      "UserDetails": {
        "Department": [
          {
            "Name": "dept2"
          }
        ],
        "Projects": [
          {
            "Name": "Project3"
          },
          {
            "Name": "Project4"
          }
        ]
      }
    },
    {
      "UserId": 3,
      "UserDetails": {
        "Department": [
          {
            "Name": "dept3"
          }
        ],
        "Projects": [
          {
            "Name": "Project5"
          },
          {
            "Name": "Project6"
          }
        ]
      }
    }
  ]
  
var filteredElements = myList.filter(x =>x.UserDetails.Department.find(d => d.Name == "dept3") || x.UserDetails.Projects.find(p => p.Name == "Project3"))
console.log(filteredElements)

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

Retrieving the value of the initial key in a nested JSON object through SQL commands

Here is an example of a JSON format: { "query": { "pages": { "294195": { "id": 294195, "title": "title 123", "detail": "detail content..." } } } } In this JSON data, I am looking to extract the information ...

Any tips for customizing the appearance of a {Switch} component from react-router-dom? I attempted to encase it in a <div> element, but it did

https://i.stack.imgur.com/4piCG.jpg https://i.stack.imgur.com/CyQH3.jpg My code attempts to modify the styling of the map component, but it seems to be influenced by the Switch component. How can I ensure that the screen fits within the 'root' ...

Submitting JSON data with a Python HTTP PUT request

How can I send a PUT request using JSON data in Python? data = [{"$TestKey": 4},{"$TestKey": 5}] Is there a method to achieve this? import requests import json url = 'http://localhost:6061/data/' data = '[{"$key": 8},{"$key": 7}]' ...

Navigating through Leaflet to reference a .json file

Looking to integrate a .json vector layer into a Leaflet.js map, which can be seen on the GitHub page here, with the source code available here. Here's a condensed version of the file for reference (full version visible on the linked GitHub page). & ...

Strategies for integrating a username-only login using Firebase without requiring a password or email address

For my class assignment, I'm developing a webapp and want to implement a login system with only a username. However, when I try sending just the username to the database, it gets stored as a child under the connection ID in Firebase. Below is the Java ...

Generate a Year attribute value using the information from the year field in a JSON document

Currently, I am exploring the functionalities showcased in this example: I am interested in adapting the following code snippet to work with my JSON file, which lacks a specific date data type field but includes a 'Year' value: // Transform Yea ...

Having trouble running the script, chrome error with message passing?

I've hit a roadblock while working on my Chrome extension and could use some assistance. The main issue I'm facing is getting the script to run when activated by the user through an on/off switch in the popup window. It seems like there might be ...

Obtain the total number of result entries

I'm working on a project involving JS and PHP. My goal is to call a PHP file using Ajax and have it return the count of result lines. I use echo for this: $connection = new PDO($source, $user); $query = "SELECT * FROM scores WHERE username = '" ...

Steps to modify the ShapeGeometry in three.js

As a beginner in three.js, I encountered an issue where updating a ShapeGeometry wasn't working as expected. This resulted in me having to remove and re-add the ShapeMesh every time. this.mesh.geometry.dispose() this.mesh.material.dispose() ...

"Incorporating a hyperlink into a newly added table row with the help

When utilizing jQuery, I am able to dynamically add rows to a table with each row containing an anchor tag. However, when attempting to populate the anchor tags with links using jQuery, the links do not appear as expected. Strangely enough, the other data ...

Create a shape using the fabric.js library that resembles a polygon

I am attempting to create a custom polygon using the following code snippet: http://jsfiddle.net/e5Xth/3/ canvas.on('mouse:move', function (options) { if (lines[0] !== null && drawingObject.type == "roof") { setStarti ...

I'm having trouble with the $locationProvider not functioning properly on my Angular webpage

I am facing an issue in my angular page where I am using a $locationProvider. However, it seems to not be functioning correctly on my web page. The console is showing an error message that says "$location in HTML5 mode requires a <base> tag to be pre ...

Improve the functionality of select[multiple] to allow for single-click modifications without the need for CMD/CTRL

I am attempting to modify the default functionality of a select element so that clicking once on its options changes their selected state. Essentially, I want to eliminate the confusing requirement of holding down shift/ctrl to select multiple options. I ...

When an image is clicked, I am attempting to access data from a Sharepoint list

In my Sharepoint list, there are three columns: Image, Title, and Description. I am using ajax to retrieve the items from the list. The images can be successfully retrieved, but my goal is to display the title and description of the clicked image when an ...

Is it possible for images underneath to receive focus when hovering over them?

I'm struggling with a layout of thumbnails on my page. We'll refer to them as A, B, C, etc. They are currently displayed like this: A, B, C, D, E, F, G, H, I, J, K, L, M, N... and so on. When you hover over one thumbnail, it enlarges by 2.5 t ...

Unraveling nested elements with the array map() method in Angular2 and Typescript: Fixing the issue of undefined property reference while mapping

Hey there! I'm currently working with Angular 4 and I have a piece of code that parses data from an API into a TypeScript array of rows. It's important to note that the code functions properly if elements like 'item.tceCampRun' and &apo ...

Decoding JSON data to a C# class using a flexible object

Upon receiving JSON data from an API, the format is as follows: { "success":true, "code":200, "total":2, "data":{ "1019588":{ "name":"(t) Bob Jones", ...

Inquiries regarding the distinctive key and component framework of Ant Design

Currently, I am in the midst of a project utilizing react, next.js, and antd. However, an error message has popped up stating: Warning: Each child in a list should have a unique "key" prop. This issue precisely stems from the absence of a uniqu ...

The synchronization between jQuery's onLoad and onDomready functions allows for seamless

When utilizing jsFiddle, I have noticed two options for initializing content using jQuery: onLoad or onDomReady. I have tested most of the scripts I've written and found no noticeable functional difference. Upon researching via Google, I discovered o ...

Tips for managing the output of an asynchronous function in TypeScript

The casesService function deals with handling an HTTP request and response to return a single object. However, due to its asynchronous nature, it currently returns an empty object (this.caseBook). My goal is for it to only return the object once it has b ...