[javascript] How to resolve TypeError: Cannot convert undefined or null to object

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 and run it on some sample values, it functions just fine. But I'm getting this error in a spec runner designed to test this.

My code:

  // five lines of comments
  var stringify = function(obj) {
  if (typeof obj === 'function') { return undefined;}  // return undefined for function
  if (typeof obj === 'undefined') { return undefined;} // return undefined for undefined
  if (typeof obj === 'number') { return obj;} // number unchanged
  if (obj === 'null') { return null;} // null unchanged
  if (typeof obj === 'boolean') { return obj;} // boolean unchanged
  if (typeof obj === 'string') { return '\"' + obj + '\"';} // string gets escaped end-quotes
  if (Array.isArray(obj)) { 
    return obj.map(function (e) {  // uses map() to create new array with stringified elements
        return stringify(e);
    });
  } else {
    var keys = Object.keys(obj);   // convert object's keys into an array
    var container = keys.map(function (k) {  // uses map() to create an array of key:(stringified)value pairs
        return k + ': ' + stringify(obj[k]);
    });
    return '{' + container.join(', ') + '}'; // returns assembled object with curly brackets
  }
};

var stringifyJSON = function(obj) {
    if (typeof stringify(obj) != 'undefined') {
        return "" + stringify(obj) + "";
    }
};

The error message I'm getting from the tester is:

TypeError: Cannot convert undefined or null to object
    at Function.keys (native)
    at stringify (stringifyJSON.js:18:22)
    at stringifyJSON (stringifyJSON.js:27:13)
    at stringifyJSONSpec.js:7:20
    at Array.forEach (native)
    at Context.<anonymous> (stringifyJSONSpec.js:5:26)
    at Test.Runnable.run (mocha.js:4039:32)
    at Runner.runTest (mocha.js:4404:10)
    at mocha.js:4450:12
    at next (mocha.js:4330:14)

It seems to fail with: stringifyJSON(null) for example

This question is related to javascript null undefined

The answer is


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

Replace

if (typeof obj === 'undefined') { return undefined;} // return undefined for undefined
if (obj === 'null') { return null;} // null unchanged

with

if (obj === undefined) { return undefined;} // return undefined for undefined 
if (obj === null) { return null;} // null unchanged

I solved the same problem in a React Native project. I solved it using this.

let data = snapshot.val();
if(data){
  let items = Object.values(data);
}
else{
  //return null
}

I have the same problem with a element in a webform. So what I did to fix it was validate. if(Object === 'null') do something


In my case, I added Lucid extension to Chrome and didn't notice the problem at that moment. After about a day of working on the problem and turning the program upside down, in a post someone had mentioned Lucid. I remembered what I had done and removed the extension from Chrome and ran the program again. The problem was gone. I am working with React. I thought this might help.


Below snippet is sufficient to understand how I encountered the same issue but in a different scenario and how I solved it using the guidance in the accepted answer. In my case I was trying to log the keys of object present in the 0th index of the 'defaultViewData' array using Object.keys() method.

defaultViewData = [{"name": "DEFAULT_VIEW_PLP","value": {"MSH25": "LIST"}}] 

console.log('DEFAULT_VIEW', Object.keys(this.props.defaultViewData[0]));

The console.log was not getting printed and I was getting the same error as posted in this question. To prevent that error I added below condition

    if(this.props.defaultViewData[0]) {
  console.log('DEFAULT_VIEW', Object.keys(this.props.defaultViewData[0]));
}

Adding this check ensured that I didn't get this error. I hope this helps for someone.

Note: This is React.js code. (although to understand the problem it doesn't matter).


If you're using Laravel, my problem was in the name of my Route. Instead:

Route::put('/reason/update', 'REASONController@update');

I wrote:

Route::put('/reason/update', 'RESONController@update');

and when I fixed the controller name, the code worked!


In my case I had an extra pair of parenthesis ()

Instead of

export default connect(
  someVariable
)(otherVariable)()

It had to be

export default connect(
  someVariable
)(otherVariable)

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);

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to null

getElementById in React Filter values only if not null using lambda in Java8 Why use Optional.of over Optional.ofNullable? How to resolve TypeError: Cannot convert undefined or null to object Check if returned value is not null and if so assign it, in one line, with one method call How do I assign a null value to a variable in PowerShell? Using COALESCE to handle NULL values in PostgreSQL How to check a Long for null in java Check if AJAX response data is empty/blank/null/undefined/0 Best way to check for "empty or null value"

Examples related to undefined

Checking for Undefined In React Raw_Input() Is Not Defined How to resolve TypeError: Cannot convert undefined or null to object "undefined" function declared in another file? Passing Variable through JavaScript from one html page to another page Javascript - removing undefined fields from an object PHP How to fix Notice: Undefined variable: Undefined Symbols for architecture x86_64: Compiling problems Undefined or null for AngularJS PHP Notice: Undefined offset: 1 with array when reading data