Explore through descendant elements and locate attributes (up to a specified number of levels)

Consider the JSON data below:

var responseData = {
  "Status": "Met",
  "Text": "Text1",
  "Id": "AAA",
  "ContentItems": [
    {
      "Selected": true,
      "Text": "Text2",
      "Id": "BBB"
    },
    {
      "Status": "Met",
      "Text": "Text3",
      "Id": "CCC",          
      "ContentItems": [
        {
          "Selected": true,
          "Text": "Text5",
          "Id": "DDD"
        },
        {
          "Status": "Met",
          "Text": "Text6",
          "Id": "EEE",
          "ContentItems": [
            {
              "Selected": true,
              "Text": "Text7",
              "Id": "FFF"
            },
            {
              "Selected": true,
              "Text": "Text8",
              "Id": "GGG"
            },
            {
              "Status": "Met",
              "Text": "Text9",
              "Id": "III",
              "ContentItems": [
                {
                  "Status": "Met",
                  "Text": "Text11",
                  "Id": "JJJ",
                  "ContentItems": [
                    {
                      "Text": "Text12",
                      "Id": "77"
                    },
                    {
                      "Status": "Met",
                      "Text": "Text13",
                      "Id": "10",
                      "ContentItems": [
                        {
                          "Text": "Text14",
                          "Id": "45"
                        },
                        {
                          "Selected": true,
                          "Text": "Text15",
                          "Id": "87"
                        },
                        {
                          "Selected": true,
                          "Text": "Text16",
                          "Id": "80"
                        }
                      ]
                    }                            
                  ]
                },
                {
                  "Status": "Met",
                  "Text": "Text17",
                  "Id": "KKK",
                  "ContentItems": [
                    {
                      "Text": "Text18",
                      "Id": "12"
                    },
                    {
                      "Status": "NotMet",
                      "Text": "Text19",
                      "Id": "14",
                      "ContentItems": [
                        {
                          "Text": "Text20",
                          "Id": "55"
                        },
                        {
                          "Selected": true,
                          "Text": "Text21",
                          "Id": "98"
                        }
                      ]
                    }                            
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
  ]
};

The requirements are as follows:

1. Return true if all "Status" values are "Met".

2. Return false if any "Status" value is "NotMet".

Since child nodes can be nested at any level, a recursive function must be used to traverse through each node and loop over the children nodes recursively.

The provided code attempts to achieve this, but it is not functioning as expected.

function checkStatusMet(responseData) {
  if (responseData.Status == 'NotMet') {
    return false;
  } else {
    if (responseData.ContentItems) {
      if (Array.isArray(responseData.ContentItems)) {
        for (var i = 0; i < responseData.ContentItems.length; i++) {
          if (responseData.ContentItems[i].ContentItems) {
            return checkStatusMet(responseData.ContentItems[i]);
          } else {
            if (responseData.ContentItems[i].Status == 'NotMet') {
              return false;
            } else {
              continue;
            }
          }
        }
        return true;
      }
    } 
  }
}

Answer №1

function checkIfStatusMet(data) {
    if (data.Status === 'NotMet') return false;
    else if (data.hasOwnProperty('ContentItems')) return data.ContentItems.every(checkIfStatusMet);
    else return true;
}

var isMet = checkIfStatusMet(response);

console.log(isMet);

Answer №2

When evaluating the statement

return isStatusMet(response.ContentItems[i]);
, it is important to note that it may result in a premature exit regardless of the status. To address this issue, the logic should be refined so that it only returns false if the recursive call returns false, allowing the loop to continue otherwise.

Consider the following revised code snippet:

if (response.ContentItems[i].ContentItems) {
    if (!isStatusMet(response.ContentItems[i])) return false;
}

Answer №3

To apply Array#every recursively, you can utilize it in case ContentItems is an array.

var data = { Status: "Met", Text: "Text1", Id: "AAA", ContentItems: [{ Selected: true, Text: "Text2", Id: "BBB" }, { Status: "Met", Text: "Text3", Id: "CCC", ContentItems: [{ Selected: true, Text: "Text5", Id: "DDD" }, { Status: "Met", Text: "Text6", Id: "EEE", ContentItems: [{ Selected: true, Text: "Text7", Id: "FFF" }, { Selected: true, Text: "Text8", Id: "GGG" }, { Status: "Met", Text: "Text9", Id: "III", ContentItems: [{ Status: "Met", Text: "Text11", Id: "JJJ", ContentItems: [{ Text: "Text12", Id: 77 }, { Status: "Met", Text: "Text13", Id: 10, ContentItems: [{ Text: "Text14", Id: 45 }, { Selected: true, Text: "Text15", Id: 87 }, { Selected: true, Text: "Text16", Id: 80 }] }] }, { Status: "Met", Text: "Text17", Id: "KKK", ContentItems: [{ Text: "Text18", Id: 12 }, { Status: "NotMet", Text: "Text19", Id: 14, ContentItems: [{ Text: "Text20", Id: 55 }, { Selected: true, Text: "Text21", Id: 98 }] }] }] }] }] }] },
    result = [data].every(function iter(a) {
        return a.Status !== 'NotMet' && (!Array.isArray(a.ContentItems) || a.ContentItems.every(iter));
    });

console.log(result);

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

Unrecognized files located within the same directory

My main.html file located in the templates folder also contains three additional files: date.js, daterangepicker.js, and daterangepicker.css. Despite including them in the head of the HTML as shown below: <script type="text/javascript" src="date.js"> ...

Stop the Router from Displaying the Page momentarily prior to Redirecting

Currently, I have set up a session context for my NextJS application where users accessing pages within the /app/ directory are required to undergo an authorization check before being granted access. Although the logic is functioning correctly in redirect ...

Mastering ReactJS: Error Encountered - Unexpected import Token

Just getting started with ReactJS and trying out some code from egghead.io. Unfortunately, I keep running into this error: Uncaught SyntaxError: Unexpected token import I've tried loading babel again and making sure to follow the lesson step by step ...

Clicking on the parent page prevents the hyperlink inside the iframe from working as expected

I am having an issue with a hyperlink inside an iframe. When I click on it in the parent page, it doesn't work. Here is how it is set up: iframe.html <h1>I'm inner page!</h1> <a id="shared" class="btn" href=&q ...

Creating a line between two points in raphael

Hello there, I'm looking to create a line between two points in Raphael. Could you please provide me with some examples or guidance on how to achieve this? Thanks a lot!) ...

Customize Popover Color in SelectField Component

Looking to customize the SelectField's popover background color in material-ui. Is this possible? After exploring the generated theme, it seems that there is no option for configuring the selectField or popover. Attempted adjusting the menu's ba ...

A Javascript callback function does not alter the contents of an array

I have been working on a project to create a task list page, where I retrieve the items from a mongodb database. When I use console.log(item) within the callback function, each item is printed successfully. However, when I use console.log(items) outside o ...

Implementing a function or template from one component into another within a Vue.js application, despite lacking a direct connection between the two components

Working on my Vue.js app, I encountered an interesting challenge: The layout of the app is simple: it consists of a header, a main view, and a navigation section at the bottom. Depending on the current page the user is on, I want to display a main action ...

The Ultimate Guide to Initializing Variables in UI Router State Access

In my application, I have defined 2 states. One is "tickets" which matches /tickets ... $stateProvider // defines the states of my application .state("tickets", { // assigns properties to each state url: "/tickets", // route templateUrl: "m ...

Constantly positioning the text cursor over the Textbox

I am currently in the process of developing a webpage that will feature only one text box for displaying information based on the input data provided. Our strategy involves utilizing either a Barcode Scanner or Magnetic Swipe as well as a Touch Screen Moni ...

Ways of assigning a null value to a key in a JSON body request

I am facing an issue with passing a null value to a key using a POST request in an API. I want to send JSON data where Exp and TeamID should be null, like below: { "ID":162617, "TextKey":"107737", "Exp":nul ...

Issue: Headers cannot be set again once they have been sent during page reload

Whenever I attempt to refresh a specific page, I encounter an Error: Can't set headers after they are sent. Interestingly, when I click on a link to navigate to that page, the error doesn't occur. I have meticulously reviewed the sequence of even ...

Is there a discrepancy in speed between Node.js http.get and Google Chrome's $.get function?

Recently, while experimenting with node.js, I decided to test out the following code snippet: var http = require("http"); function get() { var headers = { 'Accept-Encoding': 'gzip' }; var startedAt = new Date().get ...

Understanding the implementation of public and private methods in mixins in Vue2

While I've come across documentation on the following implementation, I find myself struggling to visualize how it can be executed. // A more advanced alternative! var myGreatMixin = { // ... methods: { publicMethod() { // ... myPr ...

Invoke the parent method within the child application

I have a checkbox on the child app controller. When the user clicks it, I need to call a method from the parent controller: Parent app controller: <div ng-controller="ParentCntr as parentCntr"> <child-app></child-app> </div> C ...

Encountered an Unexpected Token SyntaxError in Node.js

When setting up the routers for the API, I have defined them for both POST and GET requests like this: var bookRouter = express.Router(); bookRouter.route('/Books') .post(function(req, res) { var bok = new book(req.body); con ...

Storing Byte Array in a File using JavaScript

I am working on a Java REST webservice that returns documents as byte array. I am trying to write JavaScript code that will retrieve the response from the webservice and save it to a file for downloading as a PDF. However, when testing my sample code, the ...

Ways to display the ping of a game server on your screen

Is there a way to display the game server's ping on the screen like in the example below? this.tfEnter.text = ShowPing + " ms"; Sometimes the code snippets provided in examples may not function properly. Channel List Image: https://i.stack ...

Refine the Crossfilter dimension according to the specified date range

What is the proper way to filter a date range using Crossfilter? The code above does not seem to yield any results, but I am certain that there are records within that specified time period. Var myDimension = CrossFilterObj.dimension(function(d) { retur ...

How can you ensure that it selects a random number to retrieve items from an array?

I am experiencing an issue with some code I wrote. Instead of displaying a random object from the array as intended, it is showing the random number used to try and display an object. <html> <body> <h1>HTML random objects< ...