How to handle undefined object property in angular 5 - javascript

I tried to fix the undefined error by setting the object property value to an empty string but its still giving the error as mentioned below:
ERROR TypeError: Cannot read property 'notes' of undefined
TS
let notes;
if (typeof manufacturer_field.manufacturer_guidelines[0].notes == undefined){
notes = '';
} else {
notes = manufacturer_field.manufacturer_guidelines[0].notes;
}
HTML
<p *ngIf="field.notes?.length">{{field.notes}}</p>
I referred this answer but that didn't work: How to handle 'undefined' in javascript

If notes array element 0 is undefined, then this will throw an error:
if (typeof manufacturer_field.manufacturer_guidelines[0].notes == undefined){
because you are checking if the property is undefined, when what is actually undefined is the .manufacturer_guidelines[0] item.
instead, you can do:
if (!manufacturer_field.manufacturer_guidelines[0]){
manufacturer_field.manufacturer_guidelines[0] = (assign it whatever value belong to this sort of item, and then once you know it is valid, then add notes)
}
Also, you are assigning the string to "notes" variable, not the actual array item.
So lets say i had a cars array:
if (!cars[0]) {
cars[0] = <Car>{};
cars[0].color = "blue";
}

Related

parse value from array of object: error undefined is not iterable

I would like to get the value from array under of object and also provide some error checking. I have following code to check if key exist and if value of key is array type or not. if yes, I would like to get the value from the key. it seems ok, but any better way I can get value? I tried to use const [value] = obj?.the_key but get exception Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator)) if
value from the_key is not array or the_key does not exist under object
const obj = {'theKey': ['correct value']}
const hasKey = obj['theKey'] !== undefined && Array.isArray(obj.theKey)
if (!hasKey) console.log('null')
const [value] = obj.theKey
console.log(value)
You can use the hasOwnProperty and isArray functions to check if your object has the key / property that you are looking for.
const obj = { 'theKey' : ['correct value'] };
let hasKey = obj.hasOwnProperty('theKey'); // This will return true / false
if (!hasKey) { // key does not exist
// error handling logic
}
Then you can check the data type of the value if it is array or not
if (hasKey) {
let keyVal = obj.theKey;
if (Array.isArray(keyVal)) { // returns true or false
// business logic with array
} else { // key value is not array
// error handling
}
}

Can not assign variable because type is null?

canvas.getActiveObject().type returns the type of the currently active element in the canvas.
var type = canvas.getActiveObject().type;
if(type){
console.log(type);
}
But when no element is active, I get TypeError, which of course happens because no element is active so there is nothing to getActiveObject from.
TypeError: canvas.getActiveObject(...) is null
Why can't I assign a variable when the activeObject is null?
Same error happens, when I try
var type = '';
if(canvas.getActiveObject().type){
type = canvas.getActiveObject().type
}
canvas.getActiveObject() is returning null.
That means that canvas.getActiveObject().type is the same as null.type.
Referencing any member of null will throw an exception.
You can solve this any number of ways
Three lines of code:
let type = '';
if(canvas.getActiveObject()) {
type = canvas.getActiveObject().type;
}
Or a one-liner:
let type = canvas.getActiveObject()
? canvas.getActiveObject().type
: '';
Or a more compact one-liner:
let type = (canvas.getActiveObject() || { type: ''}).type;
You can't access a null value like an object, I think you should safely access the value like.
var type = '';
if(canvas.getActiveObject() && canvas.getActiveObject().type){
type = canvas.getActiveObject().type
}
It looks like you're trying to access the property type returned by the function getActiveObject(), but since the function returns null, accessing the type property is throwing an error. What you need to do instead is check the return value of getActiveObject() before trying to access any of its members.
The snippet below, which is based on your code, instead checks that the active object returned is not null before attempting to access the members that reside within it.
var activeObject = canvas.getActiveObject();
if (activeObject) {
console.log(activeObject.type);
}

testing for uninitialized array element not working

I'm trying to test if an array has the second dimension added. It it does I push the new record onto it, if it doesn't I add the second dimension then do the push. I've read in multiple places the way to test for the 2nd dimension being undefined, but it is not working for me. Here's the code:
if ( typeof missionData[numMissions][0] === 'undefined') {
missionData[numMissions] = [];
missionData[numMissions].push(missionRecords.record[index])
}
else {
console.log('both array dimensions exist, pushing record');
missionData[numMissions].push(missionRecords.record[index]);
}
When it executes I get the following error:
controller.js:710 Uncaught TypeError: Cannot read property '0' of undefined
Everything I've read tells me what I'm doing is correct, but obviously it is not. What am I missing?
Thanks.....
The issue is that you are trying to access the element at 0 position of an array that does not exists, so you get that error. And you can be more DRY as you are always going to push the missionRecords.record[index] anyway:
//If undefined you can just use the !(not) operator.
if (!missionData[numMissions]) {
missionData[numMissions] = [];
}
missionData[numMissions].push(missionRecords.record[index]
missionData[numMissions] itself the array.
You just don't need to access the 0th element. Check the array is there or not.
if ( typeof missionData[numMissions] === 'undefined') {
That's all
if ( typeof missionData[numMissions] === 'undefined') {
missionData[numMissions] = [];
missionData[numMissions].push(missionRecords.record[index])
}
else {
console.log('both array dimensions exist, pushing record');
missionData[numMissions].push(missionRecords.record[index]);
}

MSCRM 2011 Javascript condition issue

I have a problem with putting condition on javascript.
In case form I'm using below code. When i enter material code manually everything is ok but when i use search help it gives me an error. When i check it on debugger i see 2 situations based on my method of entering code.
Can you help me to improve my code below, its not working properly.
Gives me error on step if (lookuptextvalue.name_Value.value)if i enter material code using search help.
function matName() {
var lookupObject = Xrm.Page.getAttribute("new_material");
if (lookupObject != null)
{
var lookUpObjectValue = lookupObject.getValue();
if ((lookUpObjectValue != null))
{
var lookuptextvalue = lookUpObjectValue[0].keyValues;
if (lookuptextvalue.name_Value.value) {
var lookuptextvaluex = lookUpObjectValue[0].keyValues.name_Value.value;
}
else if(lookuptextvalue.name.value) {
var lookuptextvaluex = lookUpObjectValue[0].keyValues.name.value;
}
var lookupid = lookUpObjectValue[0].id;
Xrm.Page.getAttribute("new_matname").setValue(lookuptextvaluex);
}
else {
Xrm.Page.getAttribute("new_matname").setValue();
}
}
}
Thanks Elda.
This is such a common error that gets people new to javascript.
if(this.myData.myValue){ ...
// throws: Uncaught TypeError: Cannot read property 'myValue' of undefined`
Many will look at myValue for the problem but if you read the error carefully it is saying it can not find the property myValue of undefined. It is not myValue that is the issue but myData that is not defined and hence can not have any properties. I personly would like the error to read Uncaught TypeError: 'myData' is undefined and has no property 'myValue' as this would stop so many getting stuck on where the problem is.
undefined is a special object in javascript and crops up everywhere. undefined is equivalent to false. undefined is assigned to a object that is not initiated. Objects that have not been defined are equal to undefined. Object that have the value undefined are not placed in JSON files. undefined is not allowed in JSON files unless it is a string. Object that have the value undefined can not have properties. undefined is a primitive type.
Examples
var myObj; // declare a variable without a value. It automatically gets undefined
// you can check if the object has a value
if(myObj === undefined){ // will be true if myObj has no value
// this does not mean it has been declare
if(myOtherObj === undefined){ // will return true as well even thought myOtherObj has not been declared
To check if a variable has been declared use void 0
// from above code snippet
if(myObj === void 0){ // is true because myObj has been declared
if(myOtherObj === void 0){ // is false because myOtherObj has not been declared.
Many people use the sort cut to determine if an object is undefined. This can cause problems if you are not careful.
if(!myObj){ // will be true if my object is undefined.
// this is bad practice because the Numbers 0, the boolean false,
// the Object null are also equivalent to false;
myObj = 0
if(!myObj){ // the test intended to find out if myObj has been defined fails
myObj = false
if(!myObj){ // again the test fails.
myObj = null
if(!myObj){ // again.
I always insist that people use the exact equivalence operator === to test for undefined
if(myObj === undefined){
Unlike C/C++ and other similar languages the order of a conditional statement is always left to right. JavaScript will exit the conditional statment as soon as it knows that it has failed. This is handy for testing for undefined
The following is also the solution to the question.
var myObj;
if(myObj !== undefined && myObj.myProperty){ // this will not crash
// because if myObj is undefined
// it will exit at the first
// condition.
// on the other hand this will
if(myObj.myProperty && myObj !== undefined){ // this will throw an error if
// myObj is undefined
undefined is equivalent to some other javascipt types
undefined == null // true
undefined == false // false
undefined == 0 // false
undefined === null // false
undefined === false // false
undefined === 0 // false
// be careful as the ! operator changes things a little
var a = undefined;
!a //true
a = 0;
!a // true
a = null;
!a // true
a = false;
!a // true
JSON files can not have undefined as a value.
{
"myObj" : undefined
}
// this is not a valid JSON file.
When stringifing an object to JSON all objects that have the value undefined will not be added to the JSON string
var myObj = {
propA : 0,
propB : "hello",
propC : undefined,
propD : null
};
var str = JSON.stringify(myObj); // will create the JSON string
{
"propA" : 0,
"propB" : "hello",
"propD" : null
}
// not that propC does not appear in the JSON
undefined is a complicated beast in JavaScript and it is best to become familiar with its uses.
Learn more at
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined

Javascript - Shorthand notation to safely check/access a property on a potential undefined object

What's the shortest syntax to check if jsonObject is not undefined before accessing its errorMessage property?
var jsonObject = SomeMethodReturningAnObject();
if (jsonObject.errorMessage === undefined) // jsonObject can be undefined and this will throw an error
/* success! */
else
alert(jsonObject.errorMessage);
You can use the && operator, since it doesn't evaluate the right-hand side if the left-hand side is undefined:
if (jsonObject && jsonObject.errorMessage === undefined)
Another way to do this is to use the typeof operator.
In JS if a variable has been declared but not set a value, such as:
var x;
Then x is set to undefined so you can check for it easily by:
if(x) //x is defined
if(!x) //x is undefined
However if you try to do if(x) on a variable that hasn't even been declared, you'll get the error you allude to in your post, "ReferenceError: x is not defined".
In this case we need to use typeof - MSDN Docs - to check.
So in your case something like:
if(typeof jsonObject !== "undefined") {
//jsonObject is set
if(jsonObject.errorMessage) {
//jsonObject set, errorMessage also set
} else {
//jsonObject set, no errorMessage!
}
} else {
//jsonObject didn't get set
}
This works because if you have a variable set to an empty object, x={}, and try to get at a variable within that object that doesn't exist, eg x.y, you get undefined returned, you don't get a ReferenceError.
Be aware that the typeof operator returns a string denoting the variable type, not the type itself. So it would return "undefined" not undefined.
Also, this very similar question on SO that could help you: How to check a not-defined variable in JavaScript
Hope this helps.
Jack.
var jsonObject = SomeMethodReturningAnObject();
if (jsonObject && jsonObject.errorMessage === undefined)
/* success! */
else
alert(!jsonObject ? "jsonObject not defined" : jsonObject.errorMessage);
if(jsonObject)
{
if (!jsonObject.errorMessage)
// success..
foo()
else
alert(jsonObject.errorMessage);
}
I'll answer the shorthand notation aspect as your specific situation is better served by an existing answer. As of ECMAScript 2018 we have spread syntax, which makes the whole thing much more concise:
if ( {...jsonObject}.errorMessage ) {
// we have errorMessage
} else {
// either jsonObject or jsonObject.errorMessage are undefined / falsey
// in either case, we don't get an exception
}
A straight if / else is not the perfect fit for your situation because you actually have 3 states, 2 of which are crammed into the same if branch above.
No jsonObject: Failure
Has jsonObject, has no errorMessage: Success
Has jsonObject, has errorMessage: Failure
Why this works:
Accessing a property foo from an object obj, assuming the object is undefined, is essentially doing this:
undefined.foo //exception, obviously
Spread syntax copies properties to a new object, so you end up with an object no matter what:
typeof {...undefined} === 'object'
So by spreading obj you avoid operating directly on a potentially undefined variable.
Some more examples:
({...undefined}).foo // === undefined, no exception thrown
({...{'foo': 'bar'}}).foo // === 'bar'

Categories