How to check if a nested property exists? [duplicate] - javascript

This question already has answers here:
Access Javascript nested objects safely
(14 answers)
Closed 4 years ago.
What is the right way of checking if a nested property exists?
if (openResult.notification) {
if (openResult.notification.payload) {
if (openResult.notification.payload.additionalData) {
if (openResult.notification.payload.additionalData.sensorOpenWarning) {
// now do sth with openResult.notification.payload.additionalData
}
}
}
}

Use try catch
var obj;
try{
console.log(obj.one.two.three.four)
}catch(e){
console.log("obj is undefined")
}

You can use this abbreviate form:
const prop2 = ((obj || {}).prop1 || {}).prop2;
Applied to your code would be:
const sensorOpenWarning = ((openResult || {}).notification || {}).payload || {}).additionalData || {}).sensorOpenWarning;

Related

Javascript Variable checking shorthand [duplicate]

This question already has answers here:
Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?
(22 answers)
Closed 4 years ago.
I'm wondering if there's a shorthand way to write something like this in JavaScript
if (thingExists) {
thingExists.manipulate
}
I think I remember seeing something along the lines of
thingExists?.manipulate
but that may have been TypeScript or something.
Anyway, any knowledge on that matter is appreciated,
Thanks!
You can use && for short circuiting:
thingExists && thingExists.manipulate
thingExists.manipulate will be evaluated if and only if thingExists is truthy.
Example:
var obj = { func: function() { console.log("func is called"); } };
obj && obj.func(); // => func is called
var falsy = null;
falsy && falsy.imaginaryFunc(); // => nothing

Please explain this line of javascript code [duplicate]

This question already has answers here:
What is "x && foo()"?
(5 answers)
What does this symbol mean in JavaScript?
(1 answer)
What a strange syntax?
(3 answers)
Closed 4 years ago.
jBox.prototype.position = function (options)
{
// this line
!options && (options = {});
}
In conventional programming boolean statements are used in if else statements.
What does !options && (options = {}); translate too?
options is a json or array. What does !options mean?
options = {} is assigning a empty json to variable options, how does it return a boolean value to be used with &&.
The code:
!options && (options = {});
is the equivalent of:
if(!options) {
options = {};
}
It means that if options is a falsy value (empty) then initialize it with an empty object literal.

javascript - check if object is empty [duplicate]

This question already has answers here:
How do I test for an empty JavaScript object?
(48 answers)
Closed 1 year ago.
I am trying to create to javascript/jquery test to check if my object is empty and cannot figure it out.
Here is the object when it has something in it:
{"mergedSellerArray":{"key1114":"1120"}}
And here is the object when empty:
{"mergedSellerArray":{}}
This is the current test I have based on another SO answer but it does not work:
var sellers = JSON.stringify({mergedSellerArray});
if(Object.keys(sellers).length === 0 && sellers.constructor === Object) {
console.log("sellers is empty!");
}
You were testing sellers which is not empty because it contains mergedSellerArray. You need to test sellers.mergedSellerArray
let sellers = {
"mergedSellerArray": {}
};
if (Object.keys(sellers.mergedSellerArray).length === 0 && sellers.mergedSellerArray.constructor === Object) {
console.log("sellers is empty!");
} else {
console.log("sellers is not empty !");
}
If you are using lodash library, you have an elegant way to check an empty object, array, map or a set.
I presume you are aware of ES6 Import statement.
import {isEmpty} from "lodash"
let obj = {};
console.log(isEmpty(obj)); //Outputs true.
let arr = [];
console.log(isEmpty(arr)); //Outputs true.
obj.name="javascript";
console.log(isEmpty(obj)); //Outputs false.
So, for your code,
isEmpty(mergedSellerArray); //will return true if object is not empty.
Hope this answer helped.
This will work in modern web browser. It is quite easy and simple
const empty = {};
if(Object.keys(empty).length === 0 && empty.constructor === Object) {
console.log("Object is empty");
} else {
console.log("Object is not empty");
}
Here is in jQuery:
$(document).ready(function(){
var obj={"mergedSellerArray":{}};
alert("is empty: "+$.isEmptyObject(obj.mergedSellerArray));
var obj2={"mergedSellerArray":{"key1114":"1120"}};
alert("is empty: "+$.isEmptyObject(obj2.mergedSellerArray));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" />
jsfidle: https://jsfiddle.net/nyqgbp38/
Can create the helper function :
const isEmpty = inputObject => {
return Object.keys(inputObject).length === 0;
};
Can use it like:
let inputObject = {};
console.log(isEmpty(inputObject)) // true.
and
inputObject = {name: "xyz"};
console.log(isEmpty(inputObject)) // false

Checking if object not null before accessing property [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 6 years ago.
var how = $('how');
var id = $('myId');
if ((how != null && !how.value.blank()) || myId != null) {
return true;
} else {
alert('Error');
}
Is there an easier way to check for not null and checking if the value of that element is blank without having to do both != null and then calling value?
Since null is falsy, a slightly shorter version would be
if((how && !how.value.blank()) || myId != null) {
...
}
Note that the above code and your own snippet both assume that if how exists, it will have a property called value, and will throw an exception if this is not the case.

JavaScript check if property defined [duplicate]

This question already has answers here:
What's the simplest approach to check existence of deeply-nested object property in JavaScript? [duplicate]
(7 answers)
Closed 10 years ago.
What is the recommended way to check if an object property like obj.prop.otherprop.another is defined?
if(obj && obj.prop && obj.prop.otherprop && obj.prop.otherprop.another)
this works well, but enough ugly.
The most efficient way to do it is by checking for obj.prop.otherprop.another in a try{} catch(exception){} block. That would be the fastest if all the remaining exist; else the exception would be handled.
var a = null;
try {
a = obj.prop.otherprop.another;
} catch(e) {
obj = obj || {};
obj.prop = obj.prop || {};
obj.prop.otherprop = obj.prop.otherprop || {};
obj.prop.otherprop.another = {};
a = obj.prop.otherprop.another ;
}
Not saying this is better but ...
x = null
try {
x = obj.prop.otherprop.another;
} catch() {}
// ...
Or alternatively ...
function resolve(obj, path) {
path = path.split('.');
while (path.length && obj) obj = obj[path.shift()];
return obj;
}
x = resolve(obj, 'prop.otherprop.another');
... but I guess the actual answer is that there isn't a best-practice for this. Not that I'm aware of.
If you're in a silly mood, this would work:
if ((((obj || {}).prop || {}).anotherprop || {}).another) { ... }
But I don't know if initializing three new objects is really worth not having to repeatedly type out the path.

Categories