Error in render 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 v...

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

frederj's user avatar

frederj

1,4359 silver badges20 bronze badges

asked Apr 18, 2015 at 18:29

zahabba's user avatar

6

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.

answered Apr 18, 2015 at 18:50

veproza's user avatar

veprozaveproza

2,6741 gold badge11 silver badges10 bronze badges

2

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

Error:

let obj

Object.keys(obj)

Solution:

Object.keys(obj || {})

answered Jul 6, 2022 at 11:02

KARTHIKEYAN.A's user avatar

KARTHIKEYAN.AKARTHIKEYAN.A

16.7k6 gold badges115 silver badges130 bronze badges

2

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

answered Aug 19, 2019 at 9:21

Yuvraj Patil's user avatar

Yuvraj PatilYuvraj Patil

7,3865 gold badges52 silver badges53 bronze badges

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

answered Aug 11, 2020 at 13:24

Banzy's user avatar

BanzyBanzy

1,38013 silver badges14 bronze badges

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

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

Eduardo Cuomo's user avatar

answered Dec 13, 2021 at 7:19

heyShraddha's user avatar

2

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.

answered Apr 4, 2020 at 10:36

Behzad Akbari's user avatar

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
}

Arfeo's user avatar

Arfeo

8607 silver badges20 bronze badges

answered Dec 31, 2019 at 11:44

ziggybaba's user avatar

ziggybabaziggybaba

2243 silver badges4 bronze badges

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

Donald Duck's user avatar

Donald Duck

8,08922 gold badges74 silver badges93 bronze badges

answered Dec 31, 2019 at 19:09

Gev's user avatar

GevGev

8124 silver badges21 bronze badges

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!

David Buck's user avatar

David Buck

3,67335 gold badges33 silver badges35 bronze badges

answered Oct 8, 2020 at 3:58

Nicodemos dos Santos's user avatar

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)

answered Oct 21, 2020 at 11:38

Gabriel Arghire's user avatar

Gabriel ArghireGabriel Arghire

1,7031 gold badge16 silver badges33 bronze badges

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

answered Dec 15, 2020 at 4:57

utkarsh-k's user avatar

utkarsh-kutkarsh-k

6826 silver badges16 bronze badges

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

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

answered Jan 4, 2022 at 7:46

Sheikh Hashir's user avatar

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

answered Jul 5, 2019 at 21:08

Ivan Fernandez's user avatar

The error “TypeError: Cannot convert undefined or null to object” happens when JavaScript attempts to convert null and undefined to an object. Below you can see examples of when this error occurs.

// ❌ Uncaught TypeError: Cannot convert undefined or null to object at Function.assign
Object.assign(undefined, {});
Object.assign(null, {});

// ❌ TypeError: Cannot convert undefined or null to object at Function.keys
Object.keys(undefined);
Object.keys(null);

// ❌ TypeError: Cannot convert undefined or null to object at Function.values
Object.values(undefined);
Object.values(null);

In the previous example, notice how the Object.assign() , Object.keys() , and Object.values() methods expect a parameter o equivalent to any JavaScript object {}.

? Interestingly, if you attempt passing a number, a string, or even a boolean when using the Object.assign() , Object.keys() , and Object.values() methods, JavaScript won’t generate an error.

// ✅ No errors generated
Object.assign(1, {});
Object.assign(true, {});
Object.assign('Hello', {});

// ✅ No errors generated
Object.keys(1);
Object.keys(true);
Object.keys('Hello');

// ✅ No errors generated
Object.values(1);
Object.values(true);
Object.values('Hello');

What happens in this scenario is JavaScript attempts to identify if the values of the received parameters have the expected value type, such as a boolean, a string, a number, an object, or an array (which is a special kind of object), etc.

? If the values of the received parameters are not an expected value type, for instance, an object, JavaScript will automatically attempt to transform the values to a given value type.

That’s why the Object.assign() , Object.keys() , and Object.values() methods didn’t fail even after a value passed is different not an object.

How to solve or prevent getting the error “TypeError: Cannot convert undefined or null to object”

Fortunately, here there are different alternatives to solve or prevent getting the error “TypeError: Cannot convert undefined or null to object”:

  • Use conditional checks prior to triggering methods expecting an object.
  • Use the nullish coalescing operator (??) to use a fallback value.
  • Use the logical OR (||) operator to use a fallback value.
  • Use Try/Catch statements to detect errors.

Let’s see the examples of the solutions mentioned above. However, instead of showing the examples by explicitly passing undefineds and null s, you will see a more realistic scenario.

const CARS = [
  {
    year: 2012,
    brand: "Dodge",
    model: "Challenger",
    color: "Black"
  }
];

// the value of the 'toyota variable will be undefined
const toyota = CARS.find(car => {
  return car.brand === "Toyota";
});

// ❌ TypeError: Cannot convert undefined or null to object at Function.values
const toyotaValues = Object.values(toyota); 

In the previous snippet of code, the toyota variable is undefined because the CARS array doesn’t contain an element with a Toyota brand after running the predicate passed to the array.find() method on all the elements of the array. In fact, there’s always the possibility of expecting an undefined value from running the array.find().

Use conditional checks prior to triggering methods expecting an object

To fix the error TypeError: Cannot convert undefined or null to object at Function.values caused in the example above, use conditional checks prior to triggering the Object.values method to ensure the toyota variable is an object. Here are examples of different checks you could do.

let toyotaValues = [];

// ? Use the double exclamation marks or "double bangs" to cast a true Boolean value
// in case toyota variable is an object
if (!!toyota) {
   toyotaValues.push(...(Object.values(toyota));
}

// ? Use the keyword typeof to detect the type of the value of toyota 
if (typeof toyota !== 'undefined') {
   toyotaValues.push(...(Object.values(toyota));
}

Use the nullish coalescing operator (??) to use a fallback value

Another solution is to use the nullish coalescing operator (??) to use a fallback value object in case the original value is undefined or null.

// ✅ Using the nullish coalescing operator is a clean way to prevent errors
// ocurred from using undefined or null values
const toyotaValues = Object.values(toyota ?? {
    year: 2018,
    brand: "Toyota",
    model: "Prius",
    color: "Black"
  };

In this way, if the toyota variable is undefined or null, the Object.values() method will use the fallback object value.

{
    year: 2018,
    brand: "Toyota",
    model: "Prius",
    color: "Black"
}

Use the logical OR (||) operator to use a fallback value

Similar to the previous solution, you can use the logical OR (||) operator to use a fallback value object in case the original value is undefined or null.

// ✅ Using the logical OR (||) is a clean way to prevent errors
// ocurred from using undefined or null values
const toyotaValues = Object.values(toyota ?? {
    year: 2018,
    brand: "Toyota",
    model: "Prius",
    color: "Black"
  };

While the nullish coalescing operator and the logical OR operator seem to work in the same way, they don’t behave the same.

Use Try/Catch statements to detect errors

Finally but not least, you can wrap the logic of the code between a try and catch to prevent the code from crashing at runtime.

try {
  const CARS = [
    {
      year: 2012,
      brand: "Dodge",
      model: "Challenger",
      color: "Black"
    }
  ];
  
  // the value of the 'toyota variable will be undefined
  const toyota = CARS.find(car => {
    return car.brand === "Toyota";
  });
  
  // ❌ Expected Error: TypeError: Cannot convert undefined or null to object at Function.values
  const toyotaValues = Object.values(toyota);
  
   // ✅ The program doesn't crash at runtime even as the error is wrapped inside a try/catch
} catch (error) {
  console.error('Oh no! There was an error ', error);
}

Conclusion

All in all, the error “TypeError: Cannot convert undefined or null to object” happens when attempting to convert a null and undefined values to an object. To prevent this error from happening

  • Use conditional checks prior to triggering methods expecting an object.
  • Use the nullish coalescing operator (??) to use a fallback value.
  • Use the logical OR (||) operator to use a fallback value.
  • Use Try/Catch statements to detect errors.

If you are encountering the error: “TypeError: Cannot convert undefined or null to Object” in JavaScript and have difficulty in resolving this error. Let’s follow this guide with the explanation and examples below to solve it.

The TypeError in JavaScript occurs when you apply a specific operation to the value of Type and it’s incorrect.

Look at the example below to learn more about this error.

var x
console.log(x.length) // This Error occurs here.

Output

TypeError: Cannot read properties of undefined (reading 'length')

This error occurs when you call the length() function but variable x does not have this function.

After learning more about how TypeError in JavaScript happens, you will move to learn how to solve the error: TypeError: Cannot convert undefined or null to object In JavaScript

How does this error happen?

This error occurs when you try to operate a function with the parameter is null or undefined.

Look at the example below to learn more about this error.

var x = null
console.log(Object.keys(x)) // The Error occurs here.

Output

TypeError: Cannot convert undefined or null to object

Solve The Error “TypeError: Cannot convert undefined or null to object”

Solution 1: Check if the value is null or undefined before operating the function

You can check if the variable is null or undefined before operating to avoid encountering this error.

Look at the example below to learn more about this solution.

// Create a function to check if the variable is null or undefined and handle it.
function myFunc(x) {
    if (x == null || x == undefined) {
        console.log('The Error will occur.')
    } else {
        console.log(Object.keys(x))
    }
}
var x = {"hello": 1}
var y = null
var z = undefined

// Now, try this function with the variable 'x'.
myFunc(x)

// Try this function with the variable 'y'.
myFunc(y)

// Try this function with the variable 'z'.
myFunc(z)

Output

[ 'hello' ]
The Error will occur.
The Error will occur.

Solution 2: Use try-catch method

You can solve this problem with the try-catch method in JavaScript.

Look at the example below:

// Create a function to check if the variable is null or undefined and handle it.
function myFunc(x) {
    try {
        console.log(Object.keys(x))
    } catch (error) {
        console.log('The Error will occur.')
    }
}

var x = {"hello": 1}
var y = null
var z = undefined

// Now, try this function with the variable 'x'.
myFunc(x)

// Try this function with the variable 'y'.
myFunc(y)

// Try this function with the variable 'z'.
myFunc(z)

Output

[ 'hello' ]
The Error will occur.
The Error will occur.

Summary 

To solve the TypeError: Cannot convert undefined or null to object in JavaScript, you can check if the value is null or undefined before operating the function or using try-catch method in JavaScript. Choose the solution that is the most suitable for you. We hope this tutorial is helpful to you. Have an exciting learning experience. Thanks!

Maybe you are interested:

  • Cannot find module ‘@babel/core’ error
  • Cannot set property ‘innerHTML’ of Null in JavaScript
  • Cannot convert undefined or null to Object in JavaScript
  • To load an ES module, set “type” – “module” in JavaScript
  • How to Rename an Object’s Key in JavaScript

My name is Thomas Valen. As a software developer, I am well-versed in programming languages. Don’t worry if you’re having trouble with the C, C++, Java, Python, JavaScript, or R programming languages. I’m here to assist you!

Name of the university: PTIT
Major: IT
Programming Languages: C, C++, Java, Python, JavaScript, R

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error no boot disk has been detected or the disk has failed что делать
  • Error in procedure galaxy next day label 16
  • Error no boot disk has been detected or the disk has failed как исправить
  • Error in nvaudcapcheckdefaultendpoint rtx voice
  • Error no boot disk has been detected or the disk has failed windows xp

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии