0

I'm trying to stringify the mousewheel event using the following function. The function works fine in other instances, but in this instance I'm getting Maximum call stack size exceeded. How can I make it only return properties/methods to the nth level?

function cloneAsObject(obj) {
    if (obj === null || !(obj instanceof Object)) {
        return obj;
    }
    var temp = (obj instanceof Array) ? [] : {};
    for (var key in obj) {
        temp[key] = cloneAsObject(obj[key]);
    }
    return temp;
}
  • 1
    The problem is not the depth of recursion, but the fact you have a circular structure which you try to transform in JSON. You can adapt the method presented [here](https://stackoverflow.com/questions/11616630/json-stringify-avoid-typeerror-converting-circular-structure-to-json) to construct a string representation of the event object. – Alexandre Dupriez Mar 19 '18 at 21:59

1 Answers1

1

Edit: The original answer below leads to an error:

Uncaught TypeError: Converting circular structure to JSON

So the level of recursion is not the problem (as Alexandre Dupriez already commented). Here is a function that returns a simple string representation, ignoring nested objects and functions (see this answer Converting circular structure to JSON):

function simpleStringify (obj){
    var simpleObject = {};
    for (var prop in obj ){
        /*if (!obj.hasOwnProperty(prop)){
            continue;
        }*/
        if (typeof(obj[prop]) == 'object'){
            continue;
        }
        if (typeof(obj[prop]) == 'function'){
            continue;
        }
        simpleObject[prop] = obj[prop];
    }
    return JSON.stringify(simpleObject);
}

Original answer: Just count the recursion level with a second argument. For example:

function cloneAsObject(obj, level) {
    if (level >= 100 || obj === null || !(obj instanceof Object)) {
        return obj;
    }
    var temp = (obj instanceof Array) ? [] : {};
    for (var key in obj) {
        temp[key] = cloneAsObject(obj[key], level + 1);
    }
    return temp;
}
Denuath
  • 130
  • 1
  • 6
  • 1
    I edited my answer. Additionally here is a complete example https://jsfiddle.net/zkaosqva/73/ – Denuath Mar 19 '18 at 23:18