zahabba
zahabba

Reputation: 3231

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

Upvotes: 202

Views: 725308

Answers (15)

Sheikh Hashir
Sheikh Hashir

Reputation: 14

reactTraverser.js:6 Uncaught TypeError: Cannot convert undefined or null to object at Function.keys (<anonymous>) at reactTraverser.js:6

If you are getting this error on typeScript Try using it without Live Server this error will not be displayed

Upvotes: 0

RyanSun
RyanSun

Reputation: 1

Object.keys(obj ?? {})

It worked for me

Upvotes: 0

Nikhil Rauniyar
Nikhil Rauniyar

Reputation: 1

My API requests got expired so it was passing a null value that was giving this error.

Might as well check your API limits.enter image description here

Upvotes: 0

heyShraddha
heyShraddha

Reputation: 61

Adding Object && works before putting the object on to map.

objexts && Object.keys(objexts)?.map((objext, idx) => 

Upvotes: 5

KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20080

Make sure that object is not empty (null or undefined ).

Error:

let obj

Object.keys(obj)

Solution:

Object.keys(obj || {})

Upvotes: 38

utkarsh-k
utkarsh-k

Reputation: 983

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

Upvotes: 0

Josep Vicent Ibanez
Josep Vicent Ibanez

Reputation: 1748

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

Upvotes: 6

Gabriel Arghire
Gabriel Arghire

Reputation: 2360

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)

Upvotes: 0

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!

Upvotes: 0

Gev
Gev

Reputation: 882

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

Upvotes: 0

Behzad Akbari
Behzad Akbari

Reputation: 21

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.

Upvotes: 1

Oluwaseyi Adejugbagbe
Oluwaseyi Adejugbagbe

Reputation: 339

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
}

Upvotes: 0

Yuvraj Patil
Yuvraj Patil

Reputation: 8726

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

Upvotes: 8

Ivan Fernandez
Ivan Fernandez

Reputation: 21

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

Upvotes: -1

veproza
veproza

Reputation: 2994

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.

Upvotes: 232

Related Questions