Suppose I have javascript class Connection and I have variable that should contain array of Connection object.
How to validate the variable?
[your array of Connection].every(elem => elem instanceof Connection);
It returns true if all items in your array are Connections, false otherwise
Function that checks your need
function isAllConnections(array) {
return array.every(function(elem) {
return elem instanceof Connection;
});
}
If you just want to check the variable exists and contains values:
var myArrayOfConnections = [];
if(myArrayOfConnections && myArrayOfConnections.length) {
//do stuff
}
The first check will evaluate whether it exists, second will check the length is greater than 0
First thing is to make sure the variable is Array:
Array.isArray( x );
function isArray(x) { return x.constructor.toString().indexOf("Array") > -1;}
x instanceof Array
Then you can check each element in the array:
for(var i in x) { if( x[i].isPrototypeOf(Connection) ) }
You might use instanceof. Without elaboration, your question is a bit unclear, but this may be useful:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FOperators%2Finstanceof
Related
This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 6 years ago.
In many places in my code, I have checks similar to the one below. It's very verbose, and ugly. Is there is better way? FYI, I'm using Lodash in all my projects, so I have access to that powerful library.
if (myAssessments[orderId].report &&
myAssessments[orderId].report[categoryProductCode] &&
myAssessments[orderId].report[categoryProductCode].categories &&
myAssessments[orderId].report[categoryProductCode].categories[comment.categoryId]) {
// Do something related to
// myAssessments[orderId].report[categoryProductCode].categories[comment.categoryId]
}
Since you use lodash, you might use the has method:
_.has(obj,[orderId, 'report', categoryProductCode, 'categories', comment.categoryId])
https://lodash.com/docs/4.16.6#has
Or the get method to get the value of the object path: https://lodash.com/docs/4.16.6#get
Not elegant way but you can wrap in try catch
var result;
try{
result = myAssessments[orderId].report[categoryProductCode].categories[comment.categoryId]
}catch{}
if (result){
// do it
}
Use the built-in isset function:
if (isset(myAssessments[orderId].report) &&
isset(myAssessments[orderId].report[categoryProductCode]) &&
isset(myAssessments[orderId].report[categoryProductCode].categories) &&
isset(myAssessments[orderId].report[categoryProductCode].categories[comment.categoryId)]) {
You could use an array with all properties to check and iterate until all properties have been checked.
function checkProperties(object, keys) {
return keys.every(function (key) {
if (key in object) {
object = object[key];
return true;
}
});
}
// usage
if (checkProperties(myAssessments, [orderId, 'report', categoryProductCode, 'categories', comment.categoryId])) {
// Do something related to
// myAssessments[orderId].report[categoryProductCode].categories[comment.categoryId]
}
I have this genric function
function chckForKeyPresence(data, arr, checkLength){
var currData = data;
for(var i=0; i<arr.length; i++){
if(!currData.hasOwnProperty(arr[i]))
return false;
currData = currData[arr[i]];
}
if(checkLength)
if(currData.length==0)
return false;
return true;
}
Here 1st argument is the main data, 2nd argument is the array of properties you need to check and the third argument will check the length of the last element that it is 0 or not, it will check only if the third argument is true.
You can use it like:
if(!chckForKeyPresence(data, ["results", "tweets"], true)){
// error
return;
}
I have code that dynamically adds properties to an array.
data.tagAdded[tag.Name] = {
tag: tag,
count: 1,
};
Later in my code I need to check rather data.tagAdded has properties. If it doesn't have properties I need to do some other code. The problem is I can't figure out how to check for the existence properties.
The tagAdded = [] is always an array rather it contains properties or not, so I can't check if it is null. I can't say if property because I don't know the name of the property since it is dynamic. I can't check length because an array with properties is of length 0.
Any other way to check if properties exist?
Assuming you just want to see if you've assigned any key-value pairs to your associative array (just FYI, for what you're doing, an object might serve you better), you can do the following:
function isEmpty(o) {
return !Object.keys(o).length && !o.length;
}
var x = [];
isEmpty(x);
=> true
x['foo'] = 'bar';
isEmpty(x);
=> false
delete x.foo;
isEmpty(x);
=> true
x.push(1);
isEmpty(x);
=> false
You can try
for (var prop in tagAdded) {
if (tagAdded.hasOwnProperty(prop)) {
console.log("property exists");
}
}
There seems to have many question asked similar on counting number of element already but I am failing to implement them with mine problem.
After jquery ajax I get JSON data returned which looks something like this
Object {0: Object, 1: Object , xxxx:"asdf" ,yyyy:"asdf", zzzz:"asdf"}
I want to get number of object between this { } braces ( not counting those xxx,yyy element )
I tried .length which doesn't work
I also tried using this Length of a JavaScript object but that return the number of element in each object. I just want the number of object
Thank You
Try this:
var json = { 0: {}, 1: {}, xxxx: "asdf", yyyy: "asdf", zzzz: "asdf" };
function typeOf( obj ) {
return ({}).toString.call( obj )
.match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}
var total = 0;
for ( var o in json ) {
if ( typeOf( json[o] ) == 'object' ) {
total++;
}
}
console.log( total ); //=> 2
Everything is an object in JavaScript. The typeof operator is misleading and won't work in this case. You can use the typeOf function above that I extracted from this blog post: Fixing the JavaScript typeof operator (worth reading). There are other ways of doing it but this seems like the most straightforward.
If it's not just a coincidence that the objects are the ones with numeric property names, and the numeric properties count up sequentially, you could do something like this:
var obj = { /* your object here */ }
for (var i=0; i in obj; i++) {
// use obj[i] for something
}
// i is now equal to the number of numeric properties
This works because as soon as i is high enough that you've run out of properties the in operator will return false. Feel free to use .hasOwnProperty() instead if you prefer.
Obviously this is a specialised solution that doesn't test the type of the different properties at all. (To actually test the type see elclanrs' solution - and either way read the page he linked to.)
Say that the entire json is in a variable called json:
var total_objects = 0;
$.each(json, function () {
if (typeof this == 'object') {
total_objects++;
}
});
However, I am curious as to why you would need to know this.
You can use a customized version from the code of this question Length of Javascript Object (ie. Associative Array) and check for element's type using typeof operator and count only those which are an object (or an array).
Object.sizeObj = function(obj) {
var size = 0, key;
for (key in obj) {
if (typeof key[obj] === 'object' && obj.hasOwnProperty(key)) size++;
}
return size;
};
// Get the count of those elements which are an object
var objectsCount = Object.sizeObj(myArray);
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;
})();
I have an array variable like Array[0], and now I need to check whether that Array[0] contains value or not inside of it. What should I do?
If you have an array and call it eg. list, then you can check if it has some elements in the following manner:
if (list.length){
// has some elements (exactly list.length elements)
} else {
// does not have any elements
}
See the following for details: Documentation on length property of Array objects in JavaScript
if(array[0] !== undefined){
// array[0] is defined.
}
//pass array variable to this function
function isEmpty(array){
if(array.length == 0)
return true;
else
return false;
}
Checks if that array exists and does something if not so.
if(!array[0])
{
//do something
}