Transforming null into empty string in javascript - 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(","));

Related

How can I replace values matching a certain key in a JSON wrap in a QueryString?

I have:
queryString=`key_value="something"&type_name=user&value={"password":"Test1234"}&key_attribute=guid`
I want to replace the password of Test1234 with [HIDDEN].
If you are in node, you can just parse and then stringify the query string
var qs=require("querystring")
var temp=qs.parse(queryString)
var user=JSON.parse(temp.value)
user.password='[HIDDEN]'
temp.value=JSON.stringify(user)
queryString=qs.stringify(temp)
Browserify have also a querystring implementation, but you also want to use regexp
One way to achieve that is:
let queryString=`key_value="something"&type_name=user&value={"password":"Test1234"}&key_attribute=guid`
let modifiedString = queryString.replace(/("password":)"[\w]+"/, '$1"[HIDDEN]"')
console.log(modifiedString)
Use the URLSearchParams interface to create an iterable object out of the query string. Select the value you want to edit with the get() method of the object and parse the value to an object using JSON.parse.
Now you have the value as an object from which you can update the value of the password property.
Use the set() method to overwrite the value entry of the query string and stringify the object back to JSON.
Turn the URLSearchParams object back to a string with the toString() method.
const queryString=`key_value="something"&type_name=user&value={"password":"Test1234"}&key_attribute=guid`;
const params = new URLSearchParams(queryString);
const value = params.get('value');
const objectValue = JSON.parse(value);
objectValue.password = '[HIDDEN]';
params.set('value', JSON.stringify(objectValue));
const updatedQueryString = params.toString();
console.log(updatedQueryString);
Altho there are bunch of packages that can be used to fix this, I suggest learning how to solve it raw
Below solutions will help to understand how to make things
const queryString = `key_value="something"&type_name=user&value={"password":"Test1234"}&key_attribute=guid`;
// SOLUTION 1
// convert string to object, change key, and convert back to string
const jsonString = queryString
.split('&')
.reduce((acc, next) => {
const [key, value] = next.split('=');
acc[key] = value.indexOf('{') === 0 ? JSON.parse(value) : value;
return acc
}, {})
jsonString.value.password = '[HIDDEN]'
const solution1 = Object.keys(jsonString).map(key => {
const val = typeof jsonString[key] === 'object' ? JSON.stringify(jsonString[key]) : jsonString[key]
return `${key}=${val}`
}).join('&')
// SOLUTION 2
// Simply replace by regex using strict parameter
const solution2 = queryString.replace(/&value={"password":"(\w+)"}&/gi, '[HIDDEN]')
console.log('Using JSON.parse:', solution1)
console.log('Using regex:', solution2)

How do I Capitalize JSON file property values using Express Node.JS?

I've been trying for a couple hours to do this, most questions and examples I've seen are not addressing my problem, for instance This one here is talking about the keys, not values.
I tired using the JSON parser, but there are two issues:
How do I iterate through the values to begin with? I know there are different ways to read keys, but what about values and nested values (given that we don't know anything about what the keys or values are called).
How to actually write the value and replace it, rather than replacing the whole file, maybe something like:
key.value=key.value.toUpper();
I am looking for a solution that works for any JSON file, with absolultly no knowledge what the keys are called.
You could use replace to operate on the JSON string directly:
jsonString.replace(/"\s*:\s*"[^"]/g, match => {
return match.slice(0, -1) + match[match.length - 1].toUpperCase()
})
That would save you from having to parse the JSON, and might be a bit faster. It can be tough to write a performant comprehensive RegEx though, so it might be safer just to parse the JSON and write a little recursive function:
const uppercaseValues = obj => {
return Object.keys(obj).reduce((uppercased, key) => {
const value = obj[key]
if (typeof value === 'string') {
uppercased[key] = value[0].toUpperCase() + value.slice(1)
} else if (typeof value === 'object') {
uppercased[key] = uppercaseValues(value)
} else {
uppercased[key] = value
}
return uppercased
}, {})
}
const parsedJson = JSON.parse(jsonString)
const uppercased = uppercaseValues(parsedJson)
const xformedJson = JSON.stringify(uppercased)

Concisest way to handle undefined variables in JavaScript

I have an object that I am creating that could potentially have undefined properties.
Is there a more concise way to set the property than what I am doing below:
var ruleObj = {
factor: (ruleArray[2] ? ruleArray[2].trim() : null),
resultElseTarget: (ruleArray[10] ? ruleArray[10].trim() : null)
}
Notice how I have to repeat the variable after the ternary operator twice. The reason I'm asking is that I've run into this same type of problem several times and it doesn't seem like the best way to handle it.
Here’s a function that wraps another function to do nothing on null and undefined values:
const liftMaybe = f => x => x == null ? null : f(x);
Then you can define a trim that does nothing to undefined:
const trimMaybe = liftMaybe(x => x.trim());
and make use of it:
var ruleObj = {
factor: trimMaybe(ruleArray[2]),
resultElseTarget: trimMaybe(ruleArray[10]),
};
It differs from your original in its handling of empty strings, but I don’t know if that was intentional or if it’s even relevant.
Conciseness is one thing but with Javascript the bigger concern is readability and type checking.
In your example, if the value of ruleArray[2] is a boolean then it'd evaluate to false and set factor to null. Maybe that's what you want but just looking at your example code right now, I'd assume your ruleArray contains bools and not potential undefines.
The better way is to write a function to do null check
EDIT: someone was faster than me :) https://stackoverflow.com/a/46436844/643084
EDIT2: the other answer is great but i'd like to just make a note. null should not be treated the same as undefined even though they evaluate the same most of the times.
Some things:
Since you're checking indexes, you'd need to make sure that you have a length of at least the size you want. Otherwise ruleArray[10] can throw you and out of range error.
Assuming you are certain that you have the right number of elements in your array, you can use this to check a var for undefined, this is common to check incoming arguments (say you had something like function ( arg1, arg2 ) ):
arg1 = arg1 || 'some_default';
In your case, again assuming your array is long enough:
factor: ( ruleArray[2] || 'some other default' );
(Why would you set it to null if that's what you are trying to avoid).
If you're wondering, "is there a way to access an index that doesn't exist and just return null", the answer is "maybe...but I wouldn't".
Note, if the value is indeed falsy (say, 0, '', or false), you may not get what you expect, in which case you'd want to check for something more explicit, like null.
I get a lot of use of out the terse "something = thisValIfNotFalsy || someOtherDefaultVal. Like anything though careful when and where, etc.
You could do something like:
var ruleArray = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
function formatRule(rule) {
if (!rule) return null
return rule.trim()
}
var ruleObj = {
factor: formatRule(ruleArray[2]),
resultElseTarget: formatRule(ruleArray[10])
}
console.log(ruleObj.factor)
console.log(ruleObj.resultElseTarget)
We created a pure function that is tasked with producing either null or a trimmed value, which avoids duplicating this logic elsewhere.
Is there a more concise way
So far all answers seem to assume your input is either a string or null / undefined. For me I'd say the check for null / undefined is the wrong way round. You can only call trim on a string, so why not check it's a string?. It would also mean NaN / Numbers / Arrays etc, would not error. I'm assuming what your wanting this function to do is trim a string if it's a string, so I would also say you should pass the original value if not a string.
Maybe that's what #zaftcoAgeiha meant when he talking about not treating null & undefined the same.
Anyway, here is an example. Notice how numbers are still passed, but hello gets trimmed.
const ruleArray = [];
ruleArray[2] = null;
ruleArray[5] = 7;
ruleArray[7] = 'Helllo ';
const trimIfString = (x) => typeof x === 'string' ? x.trim() : x;
var ruleObj = {
factor: trimIfString(ruleArray[2]),
resultElseTarget: trimIfString(ruleArray[5]),
hello: trimIfString(ruleArray[7])
}
console.log(ruleObj);
You can use a function pattern and set default parameter with AND && operator when passing the parameter to check if variable is defined, if not set element value to null. You can include further checks to determine if variable is passed is a string.
let ruleArray = [];
ruleArray[10] = "def ";
let ruleFn = (factor = null, resultElseTarget = null) =>
({factor, resultElseTarget});
let ruleObj = ruleFn(ruleArray[2] && ruleArray[2].trim()
, ruleArray[10] && ruleArray[10].trim());
console.log(ruleObj, ruleObj.factor === null);

Find Values in Object Array from a List

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.

jQuery JSON to string?

Instead of going JSON a json string and using $.parseJSON, I need to take my object and store it in a variable as string representing JSON.
(A library I'm dealing with expects a malformed JSON type so I need to mess around with it to get it to work.)
What's the best way to do this?
Edit: You should use the json2.js library from Douglas Crockford instead of implementing the code below. It provides some extra features and better/older browser support.
Grab the json2.js file from: https://github.com/douglascrockford/JSON-js
// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"'+obj+'"';
return String(obj);
}
else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n]; t = typeof(v);
if (t == "string") v = '"'+v+'"';
else if (t == "object" && v !== null) v = JSON.stringify(v);
json.push((arr ? "" : '"' + n + '":') + String(v));
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
};
var tmp = {one: 1, two: "2"};
JSON.stringify(tmp); // '{"one":1,"two":"2"}'
Code from: http://www.sitepoint.com/blogs/2009/08/19/javascript-json-serialization/
I use
$.param(jsonObj)
which gets me the string.
Most browsers have a native JSON object these days, which includes parse and stringify methods. So just try JSON.stringify({}) and see if you get "{}". You can even pass in parameters to filter out keys or to do pretty-printing, e.g. JSON.stringify({a:1,b:2}, null, 2) puts a newline and 2 spaces in front of each key.
JSON.stringify({a:1,b:2}, null, 2)
gives
"{\n \"a\": 1,\n \"b\": 2\n}"
which prints as
{
"a": 1,
"b": 2
}
As for the messing around part of your question, use the second parameter. From http://www.javascriptkit.com/jsref/json.shtml :
The replacer parameter can either be a function or an array of
String/Numbers. It steps through each member within the JSON object to
let you decide what value each member should be changed to. As a
function it can return:
A number, string, or Boolean, which replaces the property's original value with the returned one.
An object, which is serialized then returned. Object methods or functions are not allowed, and are removed instead.
Null, which causes the property to be removed.
As an array, the values defined inside it corresponds to the names of
the properties inside the JSON object that should be retained when
converted into a JSON object.
The best way I have found is to use jQuery JSON
You could parse the JSON to an object, then create your malformed JSON from the ajavscript object. This may not be the best performance-wise, tho.
Otherwise, if you only need to make very small changes to the string, just treat it as a string, and mangle it using standard javascript.

Categories