Check if Javascript boolean is set? [duplicate] - javascript

This question already has answers here:
How do I check if an object has a specific property in JavaScript?
(31 answers)
Closed 6 years ago.
What is the best way to determine if a Javascript boolean is set? Here's an example of what I've been doing. It seems a bit excessive but I need to determine if a value is actually set, not just if it's true:
function doSomething (params, defaults) {
params = params || {};
defaults = defaults || {};
var required = (params.required === true || params.required === false)
? params.required
: (defaults.required === true || defaults.required === false)
? defaults.required
: true;
if (required) {
// perform logic
}
}

If a value hasn't been set that means it's undefined.
function printStuff(params) {
if (params.hello !== undefined) {
console.log(params.hello);
} else {
console.log('Hello, ');
}
}
printStuff({ });
printStuff({
hello: 'World'
});
To further drive the point home, here's how it can be used with booleans.
function schrodinger(params) {
if (params.dead === undefined) {
console.log('The cat is neither dead nor alive');
} else if (params.dead) {
console.log('The cat is dead');
} else if (!params.dead) {
console.log('The cat is alive');
}
}
schrodinger({
// Not specified
});
schrodinger({
dead: true
});
schrodinger({
dead: false
});

If you want to check whether an object has a specific property, that's the in keyword:
'required' in params
There's also the hasOwnProperty method, if you need to exclude properties inherited from a prototype (you probably don't for this case):
params.hasOwnProperty('required')

Would this solve your problem?
if(required!=undefined)

Related

How to use ternary operator using _.map in angularjs

I need to return true or false based on some condition, I am not getting the cleaner code to do this:
I need to hide or show some elements on UI based on this condition which should return true or false:
scope.isDataEnabled =function(options){ //Here if supppose a comes,
// then i need to send true, otherwise false
if(!$rootScope.currentProduct.id ==
ProductConstants.BB_PRODUCT_ID){
return true;
}
else{
_.map( $rootScope.currentUser.permissions, permissionObj =>{
// permissions is an Array
return (permissionObj.module == "DATA" &&
permissionObj.values == "b" && options=="a") //need to send true
//if this condition satisfies
});
}
return false; //after returning true,
//it comes to this line and sets to false
}
Please help me guide, what i should use, to achieve it. I was thinking of using ternary operator, but not getting how to use it inside map.
Simplifying your code to a minimal test scenario that can be manipulated (and just use plain old ES20xx) may help. Something like:
let $rootScope = {
currentProduct: {
id: `x`
},
currentUser: {
permissions: [{
module: `BB_DATASET`,
values: `b`
}, {
module: `some`,
values: `a`
}]
}
};
const ProductConstants = {
BB_PRODUCT_ID: `y`
}
console.log(testMe(`a`)); // true (currentProduct.id not BB_PRODUCT_ID)
ProductConstants.BB_PRODUCT_ID = `x`;
console.log(testMe(`a`)); // true (module && values && options)
$rootScope.currentUser.permissions[0].module = `AA_DATASET`;
console.log(testMe(`a`)); // false (module not BB_DATASET)
$rootScope.currentUser.permissions[0].module = `BB_DATASET`;
console.log(testMe(`b`)); // false (options not `a`)
$rootScope.currentUser.permissions[0].values = `c`;
console.log(testMe(`a`)); // false (values not `b`)
function testMe(options) {
if ($rootScope.currentProduct.id !== ProductConstants.BB_PRODUCT_ID) {
return true;
}
const found = $rootScope.currentUser.permissions.find( v =>
v.module === `BB_DATASET` &&
v.values === `b` &&
options == `a`);
return found ? true : false;
}
.as-console-wrapper {
top: 0;
max-height: 100% !important;
}
Firstly, the return inside of the map function will not return the value to the outer function, you are only returning the result to the map function itself. The result of the map function is never being returned.
Also, I think you might want to use _.some instead of map. map is used for transforming data, while some is used to check if something matches a condition.
return _.some($rootScope.currentUser.permissions, permissionObj => {
return (permissionObj.module == "BB_DATASET"
&& permissionObj.values == "b"
&& options=="a")
});
This will check if any of the permissions match the given condition. Alternatively you can use _.all if you want everything to match the condition.

Object extensions in nodeJS

Is it possible to have object extensions in JavaScript? For example
Extensions.js
function any.isNullOrEmpty() {
if (this == null || this == "") {
return true
}
return false
}
app.js
var x = ""
console.log(x.isNullOrEmpty()) //should log true
is this possible? How do I do it?
You could add a method to the Object prototype, and use the valueOf method to get the value of the string:
...but, because null is a primitive that cannot have a method, the only way I can think of to get the target to be null would be to use call, apply or bind.
But you would never do this in production code, because modifying the prototype of built-in objects is discouraged.
'use strict' // important for the use of `call` and `null`
Object.prototype.isNullOrEmpty = function() { return this === null || this.valueOf() === '' }
const s = ''
console.log(s.isNullOrEmpty())
const t = null
console.log(Object.prototype.isNullOrEmpty.call(t))
You could use Object.prototype to extend this type of functionality in JavaScript.
Object.prototype.isNullOrEmpty = function() {
if (this == null || this == "") {
return true
}
return false
}
var x = "";
x.isNullOrEmpty(); // returns true
you need to add your custom method into prop type of object or array or everything u want to use your method on it.
but in your case you need to this like code below:
Object.prototype.isNullOrEmpty = function(){
if (this === null || this == "") {
return true
}
return false
}
let a = {a:'10'}
console.log(a.isNullOrEmpty())
function validateValue(value){
function isNullEmpty(){
return (value === void (0) || value == null)
}
return { isNullOrEmpty }
}
}

JavaScript get nested property without breaking [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Access Javascript nested objects safely
(14 answers)
Closed 5 years ago.
I am receiving a deeply nested object. I don't know which properties will be present. If I want to get the image, I can't just do this
data.opposite.info.logo.images.s.resized_urls.s,
Imagine this comes from a system where user can leave the logo empty, then my code will break. Do I need to check the existence of properties like this?
if(data.opposite){
if(data.opposite.info)
if(data.opposite.info.images)
//...etc
}
Use javascript's try { ... } catch(e) { ... } block.
try {
url = data.opposite.info.logo.images.s.resized_urls.s; }
catch(e) {
url = ''
}
Also loadash.js has a get method that can help you with this
var url = _.get(data, 'opposite.info.logo.images.s.resized_urls.s', '');
this will traverse deep into the object if the path exists and return the 's'. If it is not there, it returns the last argument which is '' in this case.
I'm trying to get value by scan object: jsfiddle
function getObjByProperty(obj, propertyName) {
if (obj instanceof Object) {
if (obj.hasOwnProperty(propertyName)) {
return obj[propertyName];
}
for (var val in obj) {
if (obj.hasOwnProperty(val)) {
var result = getObjByProperty(obj[val], propertyName);
if (result != null) {
return result;
}
}
}
} else {
return null;
}
}
var images = getObjByProperty(data, 'images');
if (images) {
console.log(images);
}

javascript ignore-if-null operator? [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 6 years ago.
In javascript I have a lot of code like this.
if (ctrl && ctrl.main && ctrl.main.user) {
SetTheme(ctrl.main.user.theme);
}
which is annoyingly long. In other, languages you can do simply
SetTheme(ctrl?.main?.user?.theme);
Is there any way to do that in javascript?
I tried,
function safeGet(a,b) { return a ? a[b] : null; }
and
SetTheme(safeGet(safeGet(safeGet(ctrl, 'main'), 'user'), 'theme'));
But that's not very readable.
The correct short cut could be
if (((ctrl || {}).main || {}).user) { // ...
Or you could use an array as path, or a dot separated string as path and check aginst existence and return the value.
function getValue(object, path) {
return path.split('.').reduce(function (o, k) {
return (o || {})[k];
}, object);
}
var ctrl = { main: { user: { theme: 42 } } };
console.log(getValue(ctrl, "main.user.theme"));
You could create a generic function to do this by passing it the string representing the path to the nested property you want:
function getValue(object, prop, /*optional*/ valIfUndefined) {
var propsArray = prop.split(".");
while(propsArray.length > 0) {
var currentProp = propsArray.shift();
if (object.hasOwnProperty(currentProp)) {
object = object[currentProp];
} else {
if (valIfUndefined) {
return valIfUndefined;
} else {
return undefined;
}
}
}
return object;
}
Then use this on any object like:
// This will return null if any object in the path doesn't exist
if (getValue(ctrl, 'main.user', null)) {
// do something
}

How do you know if an object is JSON in javascript? [duplicate]

This question already has answers here:
How to check if it's a string or json [duplicate]
(5 answers)
Closed 8 years ago.
How do I know if a variable is JSON or if it is something else? Is there a JQuery function or something I can use to figure this out?
Based on your comments, it sounds like you don't want to know whether a string is valid JSON, but rather whether an object could be successfully encoded as JSON (e.g. doesn't contain any Date objects, instances of user-defined classes, etc.).
There are two approaches here: try to analyze the object and its "children" (watch out for recursive objects) or suck-it-and-see. If you have a JSON encoder on hand (JSON.stringify in recent browsers or a plugin such as jquery-json), the latter is probably the simpler and more robust approach:
function canJSON(value) {
try {
JSON.stringify(value);
return true;
} catch (ex) {
return false;
}
}
Analyzing an object directly requires that you be able to tell whether it is a "plain" object (i.e. created using an object literal or new Object()), which in turn requires you be able to get its prototype, which isn't always straightforward. I've found the following code to work in IE7, FF3, Opera 10, Safari 4, and Chrome (and quite likely other versions of those browsers, which I simply haven't tested).
var getPrototypeOf;
if (Object.getPrototypeOf) {
getPrototypeOf = Object.getPrototypeOf;
} else if (typeof ({}).__proto__ === "object") {
getPrototypeOf = function(object) {
return object.__proto__;
}
} else {
getPrototypeOf = function(object) {
var constructor = object.constructor;
if (Object.prototype.hasOwnProperty.call(object, "constructor")) {
var oldConstructor = constructor; // save modified value
if (!(delete object.constructor)) { // attempt to "unmask" real constructor
return null; // no mask
}
constructor = object.constructor; // obtain reference to real constructor
object.constructor = oldConstructor; // restore modified value
}
return constructor ? constructor.prototype : null;
}
}
// jQuery.isPlainObject() returns false in IE for (new Object())
function isPlainObject(value) {
if (typeof value !== "object" || value === null) {
return false;
}
var proto = getPrototypeOf(value);
// the prototype of simple objects is an object whose prototype is null
return proto !== null && getPrototypeOf(proto) === null;
}
var serializablePrimitives = { "boolean" : true, "number" : true, "string" : true }
function isSerializable(value) {
if (serializablePrimitives[typeof value] || value === null) {
return true;
}
if (value instanceof Array) {
var length = value.length;
for (var i = 0; i < length; i++) {
if (!isSerializable(value[i])) {
return false;
}
}
return true;
}
if (isPlainObject(value)) {
for (var key in value) {
if (!isSerializable(value[key])) {
return false;
}
}
return true;
}
return false;
}
So yeah… I'd recommend the try/catch approach. ;-)
function isJSON(data) {
var isJson = false
try {
// this works with JSON string and JSON object, not sure about others
var json = $.parseJSON(data);
isJson = typeof json === 'object' ;
} catch (ex) {
console.error('data is not JSON');
}
return isJson;
}
You can use [json2.js] from Douglas Crockfords JSON Github site to parse it.
JSON is an encoding method not an internal variable type.
You might load in some text that is JSON encoded that javascript then uses to populate your variables. Or you might export a string that contains a JSON encoded dataset.
The only testing I've done is to check for a string, with and without double quotes, and this passes that test. http://forum.jquery.com/topic/isjson-str
Edit:
It looks like the latest Prototype has a new implementation similar to the one linked above. http://prototypejs.org/assets/2010/10/12/prototype.js
function isJSON() {
var str = this;
if (str.blank()) return false;
str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '#');
str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
return (/^[\],:{}\s]*$/).test(str);
}

Categories

Resources