How to resolve TypeError: Cannot convert undefined or null to object

后端 未结 9 1215
生来不讨喜
生来不讨喜 2020-11-28 05:44

I\'ve written a couple of functions that effectively replicate JSON.stringify(), converting a range of values into stringified versions. When I port my code over to JSBin an

相关标签:
9条回答
  • Make sure that destination object is not empty ( null or undefined ).

    You can initialize destination object with empty object like below:

    var destinationObj = {};
    
    Object.assign(destinationObj, sourceObj);
    
    0 讨论(0)
  • 2020-11-28 06:41

    This is very useful to avoid errors when accessing properties of null or undefined objects.

    null to undefined object

    const obj = null;
    const newObj = obj || undefined;
    // newObj = undefined
    

    undefined to empty object

    const obj; 
    const newObj = obj || {};
    // newObj = {}     
    // newObj.prop = undefined, but no error here
    

    null to empty object

    const obj = null;
    const newObj = obj || {};
    // newObj = {}  
    // newObj.prop = undefined, but no error here
    
    0 讨论(0)
  • 2020-11-28 06:45

    Generic answer

    This error is caused when you call a function that expects an Object as its argument, but pass undefined or null instead, like for example

    Object.keys(null)
    Object.assign(window.UndefinedVariable, {})
    

    As that is usually by mistake, the solution is to check your code and fix the null/undefined condition so that the function either gets a proper Object, or does not get called at all.

    Object.keys({'key': 'value'})
    if (window.UndefinedVariable) {
        Object.assign(window.UndefinedVariable, {})
    }
    

    Answer specific to the code in question

    The line if (obj === 'null') { return null;} // null unchanged will not evaluate when given null, only if given the string "null". So if you pass the actual null value to your script, it will be parsed in the Object part of the code. And Object.keys(null) throws the TypeError mentioned. To fix it, use if(obj === null) {return null} - without the qoutes around null.

    0 讨论(0)
提交回复
热议问题