How to check javascript object null or not? - javascript

I have JSON like this in which every keys have some value but prescription in just another object within the object so if a prescription is an empty object so how can I check whether Prescription is null or not?
var obj={
"index":"1",
"Product_Id":"124",
"Name":"Vincent 1",
"Unit_Price":"1",
"Base_Price":5,
"Gross_Price":200,
"Quantity":200,
"Net_Price":200,
"Tax":200,
"Tax_Rate":200,
"prescription":{
}
}

The question you are asking doesn't make any sense because prescription isn't null and never will be in this example. It is simply an empty object. An empty object and null are NOT the same thing.
You also don't want to simply check for length === 0 because this can return as false at times when it is actually true...
Object.keys(obj.prescription).length === 0 && obj.constructor === Object;
will give you what you want.

You could do Object.keys(obj.prescription).length, to check if the object contains any keys.
Of course this for empty obect, as in your example, not null

How is the json object being used? I mean what are you using to parse json object? For example in javascript following code can be used:
function isEmpty(object) {
for(var key in object) {
if(obj.hasOwnProperty(key))
return false;
}
return true;
}

If your object name is obj, this will give the result you want.
Object.getOwnPropertyNames(obj.prescription).length > 0

Related

How to check whether a JSON object key is an object or string? [duplicate]

This question already has answers here:
Check if a value is an object in JavaScript
(54 answers)
Check if a variable is a string in JavaScript
(30 answers)
Closed 2 years ago.
So right now, I created an example of a JSON object where:
var myObj = {
address: {
0: ["41 Lake Avenue"]
},
name: "jake"
}
myObj itself as a whole is a JSON object, and inside it, I have two keys which are address and name respectively. So the value of the address key is also an Object since its in braces, where as the name key value is just a string.
I want to write a simple check in javascript to check whether or not the keys in myObj is an object or a string. So if its an object, it returns true where as if its not an object it returns false. Therefore for address, it would be true while for name, it would be false.
I tried looking around for some isObject() method similar to isArray() but apparently i couldn't find so I'd like some help on this so i wrote a pseudocode below for the logic:
for (i=0;i<2;i++) {
if myObj[i] is Object {
return true;}
else{
return false;}
}
You can use typeof.
Note: The question is not clear and does not explains what will happen if there multiple keys with value as an object. Since the below function will return as soon as it comes across a key whose value is a object
var myObj = {
address: {
0: ["41 Lake Avenue"]
},
name: "jake"
}
function isObject(obj) {
for (let keys in obj) {
if (typeof obj[keys] === 'object' && obj[keys] !== null) {
return true
}
}
}
console.log(isObject(myObj))
if (typeof varible === 'object') {
// is object
}
But Null is also recognized as object. So you could also proove that.
You need to use the typeof(var) operator :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
For object:
typeof yourVariable === 'object' && yourVariable !== null
For string:
typeof yourVariable === 'string'

To check the JavaScript object has a value

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
}

How do you access an object within an object from an argument in Javascript? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Accessing nested JavaScript objects with string key
I have the function
function _get(name) {
return plugin._optionsObj[name] !== undefined ?
plugin._optionsObj[name] : plugin._defaults[name];
}
I would like to be able to have objects inside of my _defaults object, but then I don't know how to retrieve them but using just one set of square brackets.
i.e.
plugin._defaults = {
val1: 1,
val2: 2,
obj1: {
someVal: 3
}
}
Is it possible to access 'someVal' from the function I have above? I tried passing 'obj1.someVal' for the argument and it didn't work. Ideas?
Edit: I have found a solution and I posted it below as an answer. I've written a very nice little function to do go through the nested values with a string and I didn't have to change my function much to implement it. I hope this helps anyone in a similar situation.
I suspect that you won't always have a one-level nested object to access, so the cleaner way to do this is to use a function that traverses an object based on a string path. Here's one that is coded as a mixin for Underscore. You can then just use it like so:
_.deep(plugin._defaults, 'obj1.someVal');
This thread also has some non-Underscore alternatives.
Pass multiple arguments, and iterate over the arguments object.
function _get(/* name1, name2, namen */) {
var item = plugin._optionsObj,
defItem = plugin._defaults;
for (var i = 0; i < arguments.length; i++) {
item = item[arguments[i]];
defItem = defItem[arguments[i]];
if (item == null || defItem == null)
break;
}
return item == null ? defItem : item;
}
var opt = _get("obj1", "someVal")
I found a solution for this problem, at least one that will accommodate myself, and I'd like to share it in case it can help someone else with this problem. My biggest difficulty is that I did not know the depth of the nested value so I wanted to find a solution that would work for deeply nested objects and without requiring to redesign anything.
/* Retrieve the nested object value by using a string.
The string should be formatted by separating the properties with a period.
#param obj object to pass to the function
propertyStr string containing properties separated by periods
#return nested object value. Note: may also return an object */
function _nestedObjVal(obj, propertyStr) {
var properties = propertyStr.split('.');
if (properties.length > 1) {
var otherProperties = propertyStr.slice(properties[0].length+1); //separate the other properties
return _nestedObjVal(obj[properties[0]], otherProperties); //continue until there are no more periods in the string
} else {
return obj[propertyStr];
}
}
function _get(name) {
if (name.indexOf('.') !== -1) {
//name contains nested object
var userDefined = _nestedObjVal(plugin._optionsObj, name);
return userDefined !== undefined ? userDefined : _nestedObjVal(plugin._defaults, name);
} else {
return plugin._optionsObj[name] !== undefined ?
plugin._optionsObj[name] : plugin._defaults[name];
}
}
To retrieve objects inside of your _defaults object you'll need to improve your _get function.
For example you may pass an array of strings (each string representing a propery name) to _get to allow access to deeply nested objects.

Finding a property in a JSON Object

I'm creating a JSON object like
tags = {"jon":["beef","pork"],"jane":["chicken","lamb"]};
which was generated using php from an array like
$arr = array(
'jon' => array('beef', 'pork'),
'jane' => array('chicken', 'lamb')
);
$tags = json_encode($arr);
And I want to check if something is in one or the other. None of these seem to work, but something like
if('lamb' in tags.jane)) {
console.log('YES');
} else {
console.log('NO');
}
writes NO to the console
if('foo' in tags.jane)) {
console.log('YES');
} else {
console.log('NO');
}
also writes NO to the console
so looking at
typeof(tags.jane);
it shows it's an "object" but
console.log(tags);
shows the following:
Object
jane: Array[2]
0: "chicken"
1: "lamb"
length: 2
__proto__: Array[0]
jon: Array[2]
0: "beef"
1: "pork"
length: 2
__proto__: Array[0]
__proto__: Object
so i thought maybe tags.jane may actually be an array and tried
if($.inArray('lamb', tags.jane)) {
console.log('YES');
} else {
console.log('NO');
}
which writes YES to the console but
if($.inArray('foo', tags.jane)) {
console.log('YES');
} else {
console.log('NO');
}
also writes YES to the console.
Am I incorrectly building the JSON Object? Not targeting the value(s) properly? Any advice is greatly appreciated. If this would be easier as an array instead of an object, I have full control to change it. I'm just a bit stumped at how I should treat this.
jQuery.inArray returns -1 when element is not found. That's true value from the POV of Javascript. Try this:
if($.inArray('foo', tags.jane) != -1) {
Your second set of answers are the way you should go. However, $.inArray returns an index, not a boolean. Any non-zero integer is true, which means when foo is not found, it returns -1 which evaluates to true and prints YES.
Similarly, $.inArray('chicken', tags.jane) would return 0 and cast to false, which is also not the answer you want.
Instead, use $.inArray('foo', tags.jane) !== -1 as your condition.
tags.name will give you the array for that person. So $.inArray("chicken",tags.jane) would see if "chicken" is in jane's tags array. If it's not, you'd get -1, otherwise you'd it's position in the array (using your example, this would return zero, the first array element).
You're using the keyword in for the wrong reason.
The statement ( prop 'in' obj ) checks to see if the object(associated array) has a property with the value of prop.
Since you're using the 'in' keyword on an array, then false is going to be returned because tags.jane is an array with indexes and not an associated array with properties.
If you want to know was values are in the array then loop through and compare.
If you want to use the 'in' keyword then convert your array to an object like so.
tags = {};
// old code
tags.jane = ['lamb', 'food'];
console.log(('lamb' in tags.jane) === false )
// new code
tags.jane = {
'lamb':1,
'food':1
}
console.log(('lamb' in tags.jane) === true )
https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in
you can not use
if('foo' in tags.jane))
it should be used as
if (1 in tags.jane)
if you want to check 'foo' is in tags.jane, try this
var inIt = (function() {
var inIt = false;
tags.jane.forEach(function(item) {
inIt = inIt || 'foo' == item;
});
return inIt;
})();

Javascript NULL Values

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) {
}

Categories