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.
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With