I am trying to loop through an array to check if email, phone and alternate phone exist in database my issue is I can't find any function or work around in Angularjs that can help me loop through the array where I have set the the listed through variable
$scope.dataCheck = {
email: $scope.TheEmail,
phone: $scope.ThePhone,
AltPhone: $scope.TheAltPhone
}
I have tried to use indexOf like below still not working
if ($scope.dataCheck.indexOf($scope.TheEmail)) {
//I call a function to check if email exist and return
}
Thank You
I should mention I am using ExpressJs and I am new to Javascript
While you are technically correct that objects in JavaScript are associative arrays, they are not Arrays as such. Compare the object property to the value you are searching for.
$scope.dataCheck = {
email: $scope.TheEmail,
phone: $scope.ThePhone,
AltPhone: $scope.TheAltPhone
}
if ($scope.dataCheck.email === $scope.TheEmail) {
//I call a function to check if email exist and return
}
If you simply want to see if the has a value, you can check
if (typeof $scope.dataCheck.email !== "undefined") { ... }
if (myArray.filter(x => !x.TheEmail || !x.ThePhone || !x.TheAltPhone).length == 0) {
// do something
}
if a value is undefined, null or empty ("") javascript will return false. Filter function will return values which contains the expression and count them with length without loop through all items.
about filter you can find here more information: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter?v=control
Hope this helps.
Related
I need help iterating over variables/state elements to create an object. I am going to iterate over firstName state, lastName state, and many more states. The code is getting way too complicated. Was wondering if there is a proper way to build an object for a graphql call? or just a better way to build an object?
I have a profile page that has forms for updating the user's account. Each form input has state and setState props. On submit of the form these values need to be checked against the previous queried information stored in the account object stored in state. I am using a graphql endpoint and when I call make the update account call, I have 3 choices for each parameter value in the graphql call For example, firstName can be
1) Null (delete in database)
2) Some non-null value (change to this value in database)
3) field does not exist in call graphql call (do nothing to that attribute)
The code below I have to do for 20 state values which is not practical.
// If there is a difference between client's firstName and queried firstName in server
if (firstName != account.firstName) {
//If we stored firstName as empty String
if(firstName === ''){
//If the firstName queried is not empty
if(account.firstName != null) {
//Set the objects first name attribute to null, so server deletes field
input['firstName'] = null;
} else {
//firstName is empty string and server value is null, so do nothing, do not add attribute firstName to object "input"
}
} else {
//firstName is not an empty string so add it to object value
input['firstName'] = firstName;
}
}
If there is a better way to do this I would love the help.
One way around it is to use the bracket notation to extract specify the key for which you want to extract the value and the value that it needs to be checked against.
function getComputedValue(value, key) {
if (value != account[key]) {
if (value === '') {
if (account[key] != null) {
input[key] = null;
} else {
}
} else {
input[key] = value;
}
}
}
let firstName = getComputedValue("Tom", "firstName");
let lastName = getComputedValue("Smith", "lastName");
There are many ways you can approach this problem. I suggest you use some of the functions Underscore JS provides :
pairs_.pairs(object)
Convert an object into a list of [key, value] pairs. The opposite of object.
_.pairs({one: 1, two: 2, three: 3});
=> [["one", 1], ["two", 2], ["three", 3]]
Then you can iterate through the array
_.each(array, function(pair) {
// Insert the input assignment code here for each key
});
I have an object array that looks like this:
UserForm
{
name:"Tom",
occupation:"Programmer",
hobbies:" ",
foodAllergy:"fish",
favoriteColor:"blue"
}
And an ValidateFieldsArray that looks like this:
["hobbies", "foodAllergy", "name"]
I need to validate that there are strings filled in from the ValidateFieldsArray in the UserForm object array. It would return false because hobbies is empty.
Currently I'm using a For loop to traverse through the validateFieldsArray and it works fine. I'm wondering if there is a better solution. I also trim the string.
I can't use lodash because I'm comparing the key not the value. I want to do something like this and add additional checks like string.trim() !=="":
_.result(_.find(UserForm, { key in ValidateFieldsArray}), value);
Using Array.every seems more appropriate to check every key in an array
var isValid = ValidateFieldsArray.every( v => UserForm[v] && UserForm[v].trim().length);
let isValid = validateFieldsArray.reduce((obj, k) => {
return (obj && obj[k].trim()) ? obj : false;
}, UserForm);
Returns the UserForm object if valid otherwise returns boolean false. Object must have a string that has more than just whitespace. If you replace let with var and the arrow function then the code is valid ES 5 and works back to IE 9.
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
Current Issue:
I am looking to verify that my JavaScript Object is empty, I am trying to use the following JQuery function jQuery.isEmptyObject however, this not returning the expected results.
Example :
var searchRequest = {
marketId: "",
officeId: "",
partnerId: "",
statusId: ""
}
if (jQuery.isEmptyObject(searchRequest)) {
$("#searchButton").prop('disabled', true);
}
Question:
How can I verify that a JavaScript Object is empty using JQuery.
emptyObject means an object without any properties. Not an object with empty properties.
/**
* #param emptyCheck Function that takes a value and returns true if it's empty to allow for flexible
* definition of a value being empty. Defaults to a simple `!` check
*/
function areAllPropsEmpty(obj, emptyCheck) {
emptyCheck = emptyCheck || (val)=> !val;
for (var prop in obj) {
if (emptyCheck(obj[prop])) return false;
}
return true;
}
It may be because you are using jQuery instead of $ (or vice versa?), there could be a conflict going on.
But you could also achieve that with native JavaScript by using:
Object.keys(searchRequest).length //4
searchRequest is not an empty object. It contains key-value pairs. An empty object is {}.
See the docs for $.isEmptyObject.
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;
})();