Parse through all objects in JavaScript in order to locate a specific object key

Currently, I am in the process of troubleshooting a system that was developed by another individual. The issue at hand involves a minified library that initiates an ajax (xhr) call to an external data source upon page load and then stores the retrieved data in an object or variable. Since the call happens immediately after page load, it cannot be intercepted using a function for registering all XHR call requests. To tackle this problem, I am attempting to iterate through all variables and objects present in the browser window with the following approach:

var foundVar = false;
loopThroughObject(this);

function loopThroughObject(obj) {
  if (!foundVar) {
    try {
      for (var name in obj) {
        if (obj[name] && {}.toString.call(obj[name]) === '[object Function]') { //ensuring the object is not a function 
        } else {
          if (name == 'searchedKey') { //identified the object with key = searchedKey
            console.log(obj[name]);
            foundVar = true;
          } else {
            setTimeout(loopThroughObject.bind(null, obj[name]), 10); //further recursion of inner objects
          }
        }
      }
    } catch (error) {}
  }
}

The challenge arises when the

setTimeout(loopThroughObject.bind(null, obj[name]), 0);
section accumulates and leads to a memory problem. I attempted the straightforward loopThroughObject(obj[name]), but encountered the "Too much recursion" error after 25000 iterations. Additionally, it appears that there may be some oversight causing the loop to navigate certain unnecessary object types. Is there anyone who can suggest a more efficient method for managing this iteration?

On a side note, I tested the code on a basic HTML page and it performed without issues:

<html>
<head>
<script>
    var test = JSON.parse("{\"searchedKey\":\"12\"}");
    </script>
</head>
<body>
</body>
</html>

Answer №1

The issue likely stems from the fact that window has multiple properties that reference itself, causing your code to get stuck in an endless loop. There might also be other interconnected references leading to circular dependencies.

To avoid this problem, you can keep track of objects already visited using a Set. Here's an improved version of your code with additional enhancements, such as checking for functions with

typeof x === "function"
:

let foundVar = false;
let seen = new Set();
loopThroughObject(this);

function loopThroughObject(obj) {
    if (!foundVar) {
        try {
            for (const name in obj) {
                const value = obj[name];
                if (typeof value !== "function") {
                    if (name == "searchedKey") { // object containing searched key is found
                        console.log(value);
                        foundVar = true;
                        break;
                    } else if (value && typeof value === "object" && !seen.has(value)) {
                        seen.add(value);
                        loopThroughObject(value); // No need for setTimeout
                    }
                }
            }
        } catch (error) {}
    }
}

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

Retrieve content from Wordpress blog including image preview

Can someone help me find a PHP script that can import posts from my WordPress blog and display them on another website, complete with a thumbnail of each blog post? Thank you in advance for your assistance! ...

Running a JavaScript animation within an Electron environment

My curiosity lies in developing man-machine interfaces using Electron. Currently, I am experimenting with a Star Trek life signs monitor demo. I came across this code that can be easily customized to create vertical and horizontal movements: http://jsfiddl ...

Issue with displaying nested React Elements from Component

I am currently facing an issue with my Collection component, which is utilizing a sub-component called RenderCollectionPieces to display UI elements. Strangely, I am able to see the data for image.name in the console but for some reason, the UI elements ar ...

Utilizing an Angular foreach loop for restructuring JSON data

I currently have an ng-repeat function that outputs arrays of objects in the following format: [ {"day":"10","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"}, {"day":"3","title":"day","summary":"summary","description" ...

Exploring AngularJS: A closer look at ngOptions expressions

I have been struggling to populate a Select element with a list of objects for ngOptions. Despite confirming that the data structure is correct and accessible, I cannot get the Select to show the options. Even when rendering the options expression on the p ...

How can I confirm that all elements have been properly reset to their original positions prior to making any further adjustments to them?

In need of some creative brainstorming, I'm working on a website design featuring ten overlapping cards. When the mouse hovers over a card, it expands while others move away. My goal is for each card to return to its original position once the cursor ...

I'm curious as to why the for-of loop within the function isn't producing the anticipated results that the regular for loop is achieving

Why is the behavior of the for...of loop different from the traditional for loop within this function? It appears that the 'el' in the for...of loop does not behave the same as iterable[i] in the regular for loop? var uniqueInOrder = function(it ...

What is the best way to connect to the requested page using the Express Framework?

Recently, I came across some code on the express tutorial pages that caught my attention. app.use(express.static('/path/to/html/files')); However, in my specific application scenario, certain requested pages must be generated dynamically. This ...

Angular implementation of a dynamic vertical full page slider similar to the one seen on www.tumblr

I'm determined to add a full-page slider to the homepage of my Angular 1.x app After testing multiple libraries, I haven't had much luck. The instructions seem incomplete and there are some bugs present. These are the libraries I've experi ...

Respond to the initial message within the "if" statement

client.on('message', message => { if (message.channel.type === 'text' && message.channel.name.toLowerCase() == "channel-2" && message.content === "test") { message.react("✅") } ...

What steps are involved in launching an outdated Angular project?

Tasked with reviving an old Angular client in my company, I found myself grappling with outdated files and missing configurations. The lack of package.json, package-lock.json, and angular.json added to the confusion, while the presence of node modules in t ...

Using Jquery to trigger a function with varying parameters by clicking on multiple buttons

I have a query about extracting values from input text fields in my code. Is there a solution for this issue? <?php for ($i=0;$i<3;$i++){ echo ('<input type="text" class="form-control" name="vec" id="vec'.$i.'" value=" ...

PHP is encountering issues when attempting to dynamically add rows using JavaScript

I have created this HTML code to dynamically generate rows: <tr > <td><?php echo $row['qty'];?></td> <td class="record"><?php echo $row['prod_name'];?></td> <td><input type ...

The padding on the button inside the v-card is not being applied as expected

I am facing an issue with the following code snippet: <v-card height="200"> <v-card-actions class="mb-0"> <v-btn flat color="orange">Share</v-btn> <v-btn flat color="orange">Explore</v-btn> & ...

Explore accessing a PHP array with multiple dimensions using Jquery Ajax

I have a PHP script that runs a SQL query on my MSSQL Server instance and returns a good result. Now, I'm attempting to manipulate the result using $.ajax in jQuery, but it seems that accessing fields in an object table via "Object.field_name" is not ...

Tips for clearing an observable in Angular version 4

In the code snippet below, an observable has been created: private permissionSubject = new Subject<any>(); permissionObservable$ = this.permissionSubject.asObservable(); constructor( public apiService: ApiService) { } updatePermissionsDat ...

Designing a structure with a stationary header, immobile sidebar navigation, and unchanging content using flexbox styling

In the development of a web application, I am utilizing FlexBox for layout design. It is important to note that I am opting for pure flexbox CSS rather than incorporating Bootstrap. Desired Layout Structure: Row1: Consists of a fixed header 64px in heigh ...

Utilizing ReactJS and PHP in Harmony

I'm currently facing issues with establishing communication between a fetch call in React and a PHP script running on my MAMP server. Unexpectedly, I am encountering errors that I am unable to troubleshoot effectively. This snippet depicts the code ...

Creating random numbers in HTML using JavaScript

Currently, I am attempting to develop an HTML random number generator using JavaScript to produce a randomized number and then notify the user of the generated number. However, I consistently encounter an error when obtaining my number, which is different ...

Client-side filtering for numerical columns using the Kendo UI Grid widget

In my Kendo UI grid widget, I have a model schema set up for a field like this: RS_LookBackDays: { type: "number", editable: true }, The columns configuration for the same field looks like this: { field: "RS_LookBackDays", title: "Rate Schedule – # Lo ...