skip to Main Content

On any modern website there are a lot of global variables of complex configuration. Some are simple strings or dates, some will be objects or arrays.

I want to search for the string hello to see if it is the value of any global variable, including nested properties/values.

For example, say this was a global variable:

nacho = {
    "a" : "one",
    "b" : [
        { "d" : "yes", "e" : "no" },
        { "d" : "alpha", "e" : "bravo" },
        { "d" : "hello", "e" : "bye" },
        { "d" : "charlie", "e" : "delta" },
    ],
    "c" : "two"
}

Then searching for hello should find nacho.b[2].d;

2

Answers


  1. Here is one way you can do that regarding your specific example:

    https://playcode.io/1789958

    Note: a stack snippet was not working due to it being a sandboxed environment, this is because we are referencing the window object.

    Login or Signup to reply.
  2. -> You can try this Code :-

        function searchGlobalVariables(value, obj, path = []) {
        // Check if the current object is an array
        if (Array.isArray(obj)) {
            // Iterate through the array elements
            obj.forEach((element, index) => {
                // Recursively search within each array element
                searchGlobalVariables(value, element, path.concat(index));
            });
        } else if (typeof obj === 'object' && obj !== null) {
            // If the current object is an object (non-null), iterate through its properties
            Object.entries(obj).forEach(([key, val]) => {
                // Recursively search within each property value
                searchGlobalVariables(value, val, path.concat(key));
            });
        } else if (obj === value) {
            // If the current value matches the search value, print the path to it
            console.log(`Found value "${value}" at ${path.join('.')}`);
        }
    }
    
    // Example global variable
    nacho = {
        "a": "one",
        "b": [
            { "d": "yes", "e": "no" },
            { "d": "alpha", "e": "bravo" },
            { "d": "hello", "e": "bye" },
            { "d": "charlie", "e": "delta" },
        ],
        "c": "two"
    };
    
    // Search for the value "hello"
    searchGlobalVariables("hello", window);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search