Find Values in Object Array from a List - javascript

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.

Related

Array of objects returning null

I have this code that formats an array of objects, which is set out how I want it. However, when I go to return the output something strange happens. If I were to just return alert_cache, it returns null. But If I were return it like alert_cache.workflow_steps it returns the data needed.
Does anyone have any idea how to get around this?
if (alert_cache.length == 0) {
alert_cache.workflow_steps = {}
alert_cache.workflow_steps[keys.workflow_step] = { "errors": [], "last_error": {}};
let alr = alert_cache.workflow_steps[keys.workflow_step];
alr.errors.push(now)
alr.last_error = {message: keys.message, url:alert.step_log_url}
}
return alert_cache;
You're using alert_cache like an array and like an object. You're checking length (as if it were an array):
if (alert_cache.length == 0) {
but you're also assigning to a non-element property:
alert_cache.workflow_steps = {}
Note that doing that will not change length.
You haven't shown how you create alert_cache to start with, but if it's an array, and if you're then using it with something that only looks at its array entries and not at its other properties (for instance, JSON.stringify), it will be empty (not null).

Transforming null into empty string in javascript

Hi can I transfrom the null string into empty string ?
I have a sample data like this
'To':['test#gmail.com','test2#gmail.com','null','test3#gmail.com','null','null']
let toEmailAddress = _.toString(To)
and now it will become
toEmailAddress =
'test#gmail.com','test2#gmail.com','null','test3#gmail.com','null','null'
How can I check or replace the 'null' into empty string or empty?
I know im gonna use _.replace or javascript .replace but I dont know how
and my final output that I need to solve is looks like this
toEmailAddress =
'test#gmail.com','test2#gmail.com','test3#gmail.com'
Since you're already using lodash, you can use _.filter (or plain old Array.filter)
What you want to achieve is filtering out noisy values and only keeping good ones. You can use the following:
_.filter(['test#gmail.com','test2#gmail.com','null','test3#gmail.com','null','null'], v => v && v !== 'null') which will give you ['test#gmail.com','test2#gmail.com','test3#gmail.com'].
Without using lodash, you can use the following: ['test#gmail.com','test2#gmail.com','null','test3#gmail.com','null','null'].filter(v => v && v !== 'null')
To = ['test#gmail.com','test2#gmail.com','null','test3#gmail.com','null','null',,,,,,,,,'test123#gmail.com'] ;
toEmailAddress = _.toString(To) becomes below:
'test#gmail.com,test2#gmail.com,null,test3#gmail.com,null,null,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,test123#gmail.com'
With replace you can use below
toEmailAddress.replace(/(null|undefined)\s*,\s*/g, '')
result would be below string if you want it back as Array just use split(',') on the resultant string
'test#gmail.com,test2#gmail.com,test3#gmail.com,test123#gmail.com'
You can use Javascript Array::filter() to eliminate 'null' strings, example:
const input = ['test#gmail.com','test2#gmail.com','null','test3#gmail.com','null',,,,'null'];
let res = input.filter(x => x !== 'null');
console.log(res.join(","));

AngularJs how to check if a value exist in an array

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.

Turning a single value into an array

In my project I often find myself checking if a value is an array.
If the value is not an array I create a single element array from it.
If the value is undefined or null, I create an empty array.
The value itself is usually either an array of objects or a single object or undefined
const array = value ? (Array.isArray(value) ? value: [value]) : [];
Is there a more succinct way of doing this (perhaps with lodash or underscore), before I decide to factor this into a separate util function?
You could do
var eventsArray = events ? [].concat(events) : [];
The .concat() function accepts both arrays and individual arguments, so either way you end up with what you want.
since you are using const in your code I assume you are using ES2015 / ES6. ES1015's
Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.
function abc(value = []) {
const array = Array.isArray(value) ? value: [value];
}
If you use ES6, you can do the following, it's cleaner than .concat();
function method(value = []) {
const array = [...value];
}
Here's a solution using lodash's castArray and isNil all wrapped up in a mixin:
_.mixin( {'asArray' : function(value){
return _.isNil(value) ? [] : _.castArray(value);
}});
Usage:
_.asArray(null) -> []
_.asArray(undefined) -> []
_.asArray(0) -> [0]
_.asArray(false) -> [false]
_.asArray([1,2,3]) -> [1,2,3]
_.asArray('wibble') -> ['wibble']
A condensed ES2020 way to ensure a variable is an array:
value = [].concat(value ?? [])
Explanation
As #VoteyDisciple explained, the concat function will concatenate single values or an arrays of values. The nullish coalescing operator (??) will use the value on the right (the second empty array) if the value on the left is null or undefined. So if value is null, it will concatenate an empty array to an empty array, which returns an empty array.
Examples
// Different inputs and outputs
values = [].concat([1,2,3] ?? []) // [1,2,3]
values = [].concat(1 ?? []) // [1]
values = [].concat(null ?? []) // []
// Wrap it in a function if you like
function array(value) {
return [].concat(value ?? [])
}
// Use it like this
values = array(values)
// Or even like this
for (let value of array(values)) {
console.log(value)
}
Even shorter solution using .flat()
There is an even slicker way to do it if you don't have to check for the undefined or null value. This basically converts the value to a singleton array if it was not an array before.
[value].flat()
Example usage
[12].flat() // Output: [12]
[[[12]]].flat() // Output: [[12]]
Removing nullish values
If you want to remove nullish values - just add a filter on top of that. This will remove all the values that are falsy.
[value].filter(x => x).flat()
Pitfalls
Due to the fact that 0 (and false) is a falsy value, if you are storing numbers in an array it is advised to explicitly compare array values with null or undefined.
[value].filter(x => x !== null && x !== undefined).flat()
In order to shorten it a bit we could use Lodash's isNil method.
[value].filter(_.isNil).flat()

Convert scalar variable to array containing variable in javascript

How would one convert 5 to [5] in JavaScript?
I have a method that uses jQuery's $.inArray and I would like it to work if someone just passes in a scalar variable by converting to an array with one entry, which would be the scalar.
If I understand you correctly, you want something like this:
function myFunction(scalarValue) {
if (typeof scalarValue != "object") {
scalarValue = [scalarValue];
}
console.log(scalarValue); // Now an array
}
Edit
If you know it's a scalar value (that it hasn't already been turned into an array) you can just do this:
var scalarArray = [scalarValue];
If you wanted a jquery answer then you can use this:
jQuery.makeArray( 5 )
scalarValue = scalarValue instanceof Array ? scalarValue : [scalarValue]

Categories