I have a this._champ object (which is undefined by default).
I browser an array, and want to add this field with a value : this._champ[champ.name][ele.infos[0].StackableRangeName] = ele.value; but at the first iteration, [champ.name] is undefined, and [ele.infos[0].StackableRangeName] is always undefined, how to manage this?
I tried this ternary operator but it isn't working:
this.champ[champ.name] != undefined ? this._champ[champ.name].push({ele.infos[0].StackableRangeName: ele.value}) : this._champ.push({champ.name: {ele.infos[0].StackableRangeName: ele.value}})
This is a common idiom for initializing something with a default value if it's not yet set:
this.champ[champ.name] = this.champ[champ.name] || []
Just check for existence of the key. and then push value:
if(this.champ && !this.champ.hasOwnProperty(champ.name)) {
this.champ[champ.name] = [];
}
this._champ[champ.name].push({ele.infos[0].StackableRangeName: ele.value});
Related
Well, I know this is would be a very common question but I tried to find the solution but no luck yet. So here is the problem statement :
Due to some condition, my object is having no values and it is empty {} and when I try to check the length of this object using Object.keys(ambassador).length OR Object.entries(ambassador).length it is giving me the error
TypeError: Cannot convert undefined or null to object.
Code sample:
const ambassador = Array.isArray(ambassadors)
? ambassadors.find((item) => {
return item.affiliate_id === affiliate.tracking_id;
})
: {};
console.log(ambassador == null); //false
console.log(typeof(ambassador)); // Object
console.log(Object.keys(ambassador).length > 0 ); //TypeError: Cannot convert undefined or null to object.
So, I got solution from the comment of Kireeti Ganisetti, He suggested to use LOADASH and it worked :)
To check if the object is empty in Javascript - React :
import _ from 'lodash';
_.isEmpty(ambassador)
As mdn says:
The value null represents the intentional absence of any object value.
It is one of JavaScript's primitive values and is treated as falsy for
boolean operations
Try to check your object whether it is not null before reading keys:
let ambassador = null;
console.log(ambassador == null); //false
console.log(typeof(ambassador)); // Object
if (ambassador)
console.log(Object.keys(ambassador).length > 0 );
An example:
let ambassador = null;
console.log(ambassador == null); //false
console.log(typeof(ambassador)); // Object
if (ambassador)
console.log(Object.keys(ambassador).length > 0 );
UPDATE:
If let ambassador = {}; then abmassador is truthy so you can check keys of the object:
let ambassador = {};
console.log(ambassador == null); //false
console.log(typeof(ambassador)); // Object
if (ambassador)
console.log(`ambassador`, Object.keys(ambassador).length > 0 );
As mdn says:
In JavaScript, a truthy value is a value that is considered true when
encountered in a Boolean context. All values are truthy unless they
are defined as falsy (i.e., except for false, 0, 0n, "", null,
undefined, and NaN).
Examples of truthy values in JavaScript (which will be coerced to true in boolean contexts, and thus execute the if block):
if (true)
if ({})
if ([])
if (42)
if ("0")
Can you tell me how to check the JavaScript object has a value ? This vm.occupantDetail.contactDetail object is neither null nor undefined.It looks like as shown below at run time.
It defines as shown below.
vm.occupantDetail = {
contactDetail: {},
};
You can find the it using
Object.keys(vm.occupantDetail.contactDetail).length
It appears from your code that your vm.occupantDetail.contactDetail object is simply an empty object, and the __proto__ property that you are seeing is the protoype property of the Object. If you want to check if an object is null, the following conditional will do the job.
if (obj == null) { ... }
However, it appears that you want to check if an object is empty, which is different. If you want to check if a specified object has no assigned properties, try the following function.
function isEmpty(map) {
for(var key in map) {
if (map.hasOwnProperty(key)) {
return false;
}
}
return true;
}
check it by jQuery.isEmptyObject()
jQuery.isEmptyObject({}); // true
jQuery.isEmptyObject({ foo: "bar" });
https://api.jquery.com/jQuery.isEmptyObject/
Check the length of your object also the length of your keys.
if (Object.keys(vm.occupantDetail.contactDetail).length > 0)
{
// vm.occupantDetail.contactDetail has values
}
Java script has many falsy values as I started learning. I have a program that gets values from a service and loads into an array like this:
function loadNames() {
Global.names = // what should I use here? undefined, null, "", 0, {} or anything else
var lnames = getLNames(); // this is doing some magic
if ( lnames.length !== 0 ) {
Global.names = new Array();
for ( var i = 0; i < lnames.length; ++i)
Global.names[i] = lnames[i];
}
}
I want to know the right way of resetting Global.names. What is most appropriate here? In code I only want to check like if ( Global.names )
PS: I can't just take the return value into Global.names as the returned object is destroyed later. Hence, I need to do a deep copy
Thanks
Taken from JavaScript: the good parts :
"The if statement changes the flow of the program based on the value of the expression. The then block is executed if the expression is truthy. Here are the falsy values:
false
null
undefined
the empty string ''
the number 0
the number NaN
"
So basically if you set your var to any of those values, you'll be able to do a if(var){...}
I think you should init
GLobal.names = [];
and than just check if Global.names.length != 0.
If you want to reset it just make it an empty array again.
I think you'd be better off to initialize it as an array and test as
if ( Global.names.length )
Also, if you're just storing strings in the array you can simplify the function as
function loadNames() {
Global.names = getLNames().concat();
}
You don't have to initialise it to anything. You can do:
if (!Global.names) Global.names = [];
// add members to Global.names
This can be one in one statement:
Global.names = Global.names : [];
If you want to reset it, then:
Global.names = [];
or
delete Global.names;
Setting it to null is good, as you know that the variable exists but hasn't been assigned a value. This way you can easily see the state - if it's undefined then you've forgotten to declare it, if it's null it has been declared but never assigned a value, and if it's an Array then you can test the length from there.
I am getting the following javascript error:
'value' is null or not an object
Can someone please let me know what is the best way to check whether an object's value is NULL in javascript as I have been using:
if ((pNonUserID !== "") || (pExtUserID !== "")){
Is this correct or is there a better way?
Thanks.
You don't have to do that:
var n=null;
if(n)alert('Not null.'); // not shown
if(!n)alert('Is null.'); // popup is shown
Your error implies otherwise:
var n=null;
alert(n.something); // Error: n is null or not an object.
In the case above, something like this should be used:
if(n)alert(n.something);
The !== operator returns true when two variables are not the same object. It doesn't look at the values of the objects at all
To test if something is null:
myVar == null
Your code was testing to see if the variable 'pNonUserId' referred to the same object as "", which can never be true as "" will always be a new instance of the empty string.
As an aside, a test such as:
var n = something();
// do stuff
if (n)
doSomethingElse();
Is a bad idea. If n was a boolean and false, but you were expecting the if block to test nullify you'll be in for a shock.
if (pNonUserID && pExtUserID)
{
// neither pNonUserId nor pExtUserID are null here
}
Any Javascript variable automatically evaluates to true when it references an object.
What you were doing are comparisons to empty strings, which are not the same as null.
null, undefined and empty string is consider as false in conditional statement.
so
if(!n) alert("n is null or undefined or empty string");
if(n) alert("n has some value");
therefor, inflagranti suggested condition will work perfectly for you
if(pNonUserID && pExtUserID) {
}
This question already has answers here:
JavaScript check if variable exists (is defined/initialized)
(32 answers)
Closed 6 years ago.
I am trying to test to see whether a Javascript variable is undefined.
You will see that I am not expecting the value of predQuery[preId] to be 'undefined' if I don't first get an alert saying "its unbelievable". But I often do, so I am guessing that my statement
predQuery[preId]=='undefined')
is not matching the undefined elements properly.
if((predQuery.length < preId) || (predQuery[preId]=="") || (predQuery[preId]=='undefined')){
alert("its unbelievable");
alert(predQuery[preId]);
queryPreds[variables] = preId;
queryObjs[variables] = objId;
predQuery[preId] = variables;
}
else {
alert(predQuery[preId]);
var predIndex = predQuery[preId];
queryPreds[predIndex] = preId;
queryObjs[predIndex] = objId;
}
I can add more code if needed.
array[index] == 'undefined' compares the value of the array index to the string "undefined".
You're probably looking for typeof array[index] == 'undefined', which compares the type.
You are checking it the array index contains a string "undefined", you should either use the typeof operator:
typeof predQuery[preId] == 'undefined'
Or use the undefined global property:
predQuery[preId] === undefined
The first way is safer, because the undefined global property is writable, and it can be changed to any other value.
predQuery[preId]=='undefined'
You're testing against the string 'undefined'; you've confused this test with the typeof test which would return a string. You probably mean to be testing against the special value undefined:
predQuery[preId]===undefined
Note the strict-equality operator to avoid the generally-unwanted match null==undefined.
However there are two ways you can get an undefined value: either preId isn't a member of predQuery, or it is a member but has a value set to the special undefined value. Often, you only want to check whether it's present or not; in that case the in operator is more appropriate:
!(preId in predQuery)
There are more (many) ways to Rome:
//=>considering predQuery[preId] is undefined:
predQuery[preId] === undefined; //=> true
undefined === predQuery[preId] //=> true
predQuery[preId] || 'it\'s unbelievable!' //=> it's unbelievable
var isdef = predQuery[preId] ? predQuery[preId] : null //=> isdef = null
cheers!
Check for
if (predQuery[preId] === undefined)
Use the strict equal to operator. See comparison operators
try: typeof(predQuery[preId])=='undefined'
or more generally: typeof(yourArray[yourIndex])=='undefined'
You're comparing "undefined" to undefined, which returns false =)
This code works very well
function isUndefined(array, index) {
return ((String(array[index]) == "undefined") ? "Yes" : "No");
}