How to make variables optional while concatenation of string? - javascript

I am manipulating string to display in UI, Data is being dynamically with below code sometime i don't get header and details so how to make IHeader and IResponse optional for the string concatenation below.
if i dont have IHeader it will break at IHeader.id and throw exception i want to display whatever data is available to render.
main.js
const data = [{
id: "header",
name: "IHeader"
}, {
id: "param",
name: "IParams"
}, {
id: "details",
name: "IResponse"
}]
function buildText(data) {
var IParams;
var IResponse;
var IHeader;
for (var item of data) {
if (item.id === "param") {
IParams = item;
} else if (item.id === "header") {
IHeader = item;
} else if (item.id === "details") {
IResponse = item;
}
}
var text = '';
text += app + '.setConfig({\n' + "env:" + getEnv() + '\n});' + '\n\n';
text += 'let param:' + IParams.name + ' ' + '=' + '' + JSON.stringify(request, null, 4) + ';\n\n';
text += ref + '(' + 'param,(result:' + ' ' + '{' + '\n' + IHeader.id + ':' + IHeader.name + '\n' + IResponse.id + ':' + IResponse.name + '\n' + '})' + ' ' +
' => {\n console.log(result); \n});';
}

1 - You can try to create an object with empty values. That'll prevent the exception.
emptyObject = {id: ""} // more empty keys, if there is
IParam = (item.id === "param") ? item : emptyObject
2 - Or ignore that concatenation of the variable if undefined or null.
if (Iparam) {
// concatenation ..
}

Related

viewing javascript console.log or opening camera on ios simulator

I implemented blinkid-react-native in react native ios app. blinkid-react-native will give me the ability to scan id's and veirfy the data on them. When i run my code i get json with only the address showing.
Since I can't open the camera to scan an id from the ios simulator. i deployed the app to test flight. i need to debug and see the javascript console.logs. I'm unable to do that from test flight?
I'm not sure about how to debug the issue? Since i can't open the camera on the ios simulator to run BlinkId and go thrugh console.logs.
here is the json the i get
here is BlinkId code
export const scanId = async () => {
console.log('BlinkId*****************');
const licenseKey = Platform.select({
ios:
'**********',
android:
'**********',
});
BlinkIDReactNative.SuccessFrameGrabberRecognizer(mrtdRecognizer);
var blinkIdCombinedRecognizer = new BlinkIDReactNative.BlinkIdCombinedRecognizer();
blinkIdCombinedRecognizer.returnFullDocumentImage = true;
blinkIdCombinedRecognizer.returnFaceImage = true;
const scanningResults = await BlinkIDReactNative.BlinkID.scanWithCamera(
new BlinkIDReactNative.BlinkIdOverlaySettings(),
new BlinkIDReactNative.RecognizerCollection([
blinkIdCombinedRecognizer /*, mrtdSuccessFrameGrabber*/,
]),
licenseKey,
)
.then((result) => handleResult(result))
.catch((e) => e);
return scanningResults;
};
console.log('BlinkId+scanningResults*****************');
console.log(this.scanningResults);
console.log('BlinkId+result1*****************');
console.log(this.result);
const handleResult = (result) => {
function buildResult(result, key) {
if (result && result != -1) {
return key + ': ' + result + '\n';
}
return '';
}
console.log('BlinkId+result2*****************');
console.log(result);
function buildDateResult(result, key) {
if (result) {
return (
key +
': ' +
result.day +
'.' +
result.month +
'.' +
result.year +
'.' +
'\n'
);
}
return '';
}
var localState = {
showFrontImageDocument: false,
resultFrontImageDocument: '',
showBackImageDocument: false,
resultBackImageDocument: '',
resultImageFace: '',
results: '',
showSuccessFrame: false,
successFrame: '',
};
console.log('BlinkId+result3*****************');
console.log(result);
if (result instanceof BlinkIDReactNative.BlinkIdCombinedRecognizerResult) {
let blinkIdResult = result;
console.log('BlinkId+blinkIdResult*****************');
console.log(blinkIdResult);
let resultString =
buildResult(blinkIdResult.firstName, 'First name') +
buildResult(blinkIdResult.lastName, 'Last name') +
buildResult(blinkIdResult.fullName, 'Full name') +
buildResult(blinkIdResult.localizedName, 'Localized name') +
buildResult(
blinkIdResult.additionalNameInformation,
'Additional name info',
) +
buildResult(blinkIdResult.address, 'Address') +
buildResult(
blinkIdResult.additionalAddressInformation,
'Additional address info',
) +
buildResult(blinkIdResult.documentNumber, 'Document number') +
buildResult(
blinkIdResult.documentAdditionalNumber,
'Additional document number',
) +
buildResult(blinkIdResult.sex, 'Sex') +
buildResult(blinkIdResult.issuingAuthority, 'Issuing authority') +
buildResult(blinkIdResult.nationality, 'Nationality') +
buildDateResult(blinkIdResult.dateOfBirth, 'Date of birth') +
buildResult(blinkIdResult.age, 'Age') +
buildDateResult(blinkIdResult.dateOfIssue, 'Date of issue') +
buildDateResult(blinkIdResult.dateOfExpiry, 'Date of expiry') +
buildResult(
blinkIdResult.dateOfExpiryPermanent,
'Date of expiry permanent',
) +
buildResult(blinkIdResult.expired, 'Expired') +
buildResult(blinkIdResult.maritalStatus, 'Martial status') +
buildResult(blinkIdResult.personalIdNumber, 'Personal id number') +
buildResult(blinkIdResult.profession, 'Profession') +
buildResult(blinkIdResult.race, 'Race') +
buildResult(blinkIdResult.religion, 'Religion') +
buildResult(blinkIdResult.residentialStatus, 'Residential status') +
buildResult(blinkIdResult.processingStatus, 'Processing status') +
buildResult(blinkIdResult.recognitionMode, 'Recognition mode');
let licenceInfo = blinkIdResult.driverLicenseDetailedInfo;
if (licenceInfo) {
resultString +=
buildResult(licenceInfo.restrictions, 'Restrictions') +
buildResult(licenceInfo.endorsements, 'Endorsements') +
buildResult(licenceInfo.vehicleClass, 'Vehicle class') +
buildResult(licenceInfo.conditions, 'Conditions');
}
// there are other fields to extract
localState.results += resultString;
// Document image is returned as Base64 encoded JPEG
if (blinkIdResult.fullDocumentFrontImage) {
localState.showFrontImageDocument = true;
localState.resultFrontImageDocument =
'data:image/jpg;base64,' + blinkIdResult.fullDocumentFrontImage;
}
if (blinkIdResult.fullDocumentBackImage) {
localState.showBackImageDocument = true;
localState.resultBackImageDocument =
'data:image/jpg;base64,' + blinkIdResult.fullDocumentBackImage;
}
// Face image is returned as Base64 encoded JPEG
if (blinkIdResult.faceImage) {
localState.showImageFace = true;
localState.resultImageFace =
'data:image/jpg;base64,' + blinkIdResult.faceImage;
}
} else {
throw JSON.stringify(result);
}
console.log('BlinkId+localState*****************');
console.log(localState);
return localState;
};

Why is *ngFor seemingly looping infinitley?

Can anyone help me understand why this ngFor seemingly gets to the end and then loops again?
Template
<div class="row">
<h2>Results</h2>
</div>
<div *ngFor="let bson of bsonResults; let i = index">
{{i}}
{{getItemContext(bson, i)}}
<!-- <mat-card class="card collection-card">
<a [routerLink]="toDetails(results.database, results.collection, bson.data._id.$oid)" data-toggle="tooltip"
title="Click to visit details page" attr.aria-label="Item Name: {{utility.getItemTitle(bson, results.nameField)}}">{{utility.getItemTitle(bson, results.nameField)}}</a>
<mat-card-content [innerHTML]="getItemContext(bson)">
{{getItemContext(bson)}}
</mat-card-content>
</mat-card> -->
</div>
Relevant methods from .ts file
getItemContext(bson, i) {
console.log(i);
console.log(bson);
if (this.searchCriteria.q !== '') {
return this.contextWithSearchString(bson);
} else {
return this.contextWithoutSearchString(bson);
}
}
contextWithSearchString(bson) {
let keys = Object.keys(bson.data);
let longString: string;
let highlightedText: string;
for (let key of keys) {
let bsonItem: string = bson.data[key];
bsonItem.toString();
if (typeof bsonItem === 'string') {
if (bsonItem.toUpperCase().includes(this.searchCriteria.q.toUpperCase())) {
let indexOfTerm = bsonItem.toUpperCase().indexOf(this.searchCriteria.q.toUpperCase());
if (bsonItem.length > 100) {
if (indexOfTerm - 50 <= 0) {
bsonItem = bsonItem.substring(0, 100) + '...';
} else {
bsonItem = '...' + bsonItem.substring(indexOfTerm - 50, indexOfTerm + 50) + '...';
}
}
if (longString === undefined) {
highlightedText = this.utility.highlight(bsonItem, this.searchCriteria.q);
longString = '<b>' + key + ': ' + '</b> ' + highlightedText + ' | ' ;
} else {
highlightedText = this.utility.highlight(bsonItem, this.searchCriteria.q);
longString = longString + '<b>' + key + ': ' + highlightedText + ' | ';
}
}
}
}
return longString;
}
contextWithoutSearchString(bson) {
let keys = Object.keys(bson.data);
let longString: string;
let i = 0;
keys.forEach(key => {
// only return strings in search context, and only return the first 4.
if (typeof (bson.data[key]) === 'string' && i < 4) {
let dataValue: string = bson.data[key];
if (dataValue.length > 100) {
dataValue = dataValue.substring(1, 100) + '...';
}
if (longString === undefined) {
longString = '<b>' + key + ': </b>' + ' ' + dataValue + ' | ';
} else {
longString = longString + '<b>' + key + ': </b> ' + dataValue + ' | ';
i++;
}
}
});
// if the item only contains objects (no strings) then just return 600 chars of the raw JSON.
if (longString === undefined) { return JSON.stringify(bson.data).substring(0, 600); } else {
return longString;
}
}
and here's how it looks on the page (..looks fine)
yet here is my console getting bombarded
Strangely enough the page is displaying the output from the getItemContext function on the page the correct amount of times. However, I put a console log at the start of the function to log my bson objects and this is continually filling up the console with objects. I stuck an index variable in to see if the count looked right and it does (bsonResults contains a 11 items). When the console has gotten up to logging out the 11th item it just starts again.

Looping over JavaScript object and adding string to end if not the last item

{
field_country: ["England", "Netherlands", "India", "Italy"],
field_continent: ["Europe"],
field_group: ["Building", "People", "Landscape"
}
I want to loop over each item and return the key and the array together with ending 'OR' for example:
field_country: "England" OR field_country: "Netherlands"
The last item should not end with 'OR' in the loop. I am not sure what the best process is for this using vanilla JS. So far my code is as follows:
Object.keys(facets).forEach(function(facetKey) {
if (facets[facetKey].length > 1) {
facetResults = facets[facetKey];
for (var i = 0; i < facetResults.length; i ++) {
if (i == 1) {
filter = "'" + facetKey + "'" + ":'" + facetResults[i] + " OR";
return filter;
} else {
filter = "'" + facetKey + "'" + ":'" + facetResults[i];
}
}
} else {
filter = "'" + facetKey + "'" + ": " + facets[facetKey] + "'";
return filter;
}
});
I would be very grateful for any assistance.
Thanks in advance.
You can do something like this with Object.entries and Array.reduce if you would like to get the final result in the form of an object:
const data = { field_country: ["England", "Netherlands", "India", "Italy"], field_continent: ["Europe"], field_group: ["Building", "People", "Landscape"] }
const result = Object.entries(data).reduce((r, [k, v]) => {
r[k] = v.join(' OR ')
return r
}, {})
console.log(result)
It is somewhat unclear what is the final format you need to result in but that should help you to get the idea. If ES6 is not an option you can convert this to:
const result = Object.entries(data).reduce(function(r, [k, v]) {
r[k] = v.join(' OR ')
return r
}, {})
So there are is no arrow function etc.
The idea is to get the arrays into the arrays of strings and use the Array.join to do the "replacement" for you via join(' OR ')
Here's the idea. In your code you are appending " or " at the end of your strings starting at index 0. I suggest you append it at the the beginning starting at index 1.
var somewords = ["ORANGE", "GREEN", "BLUE", "WHITE" ];
var retval = somewords[0];
for(var i = 1; i< somewords.length; i++)
{
retval += " or " + somewords[i];
}
console.log(retval);
//result is: ORANGE or GREEN or BLUE or WHITE
Your conditional expression if (i == 1) would only trigger on the second iteration of the loop since i will only equal 1 one time.
Try something like:
if (i < (facetResults.length - 1)) {
// only add OR if this isn't the last element of the array
filter = "'" + facetKey + "'" + ":'" + facetResults[i] + " OR";
return filter;
}
Here's your updated code:
Object.keys(facets).forEach(function(facetKey) {
if (facets[facetKey].length > 1) {
facetResults = facets[facetKey];
for (var i = 0; i < facetResults.length; i ++) {
if (i < (facetResults.length - 1)) {
filter = "'" + facetKey + "'" + ":'" + facetResults[i] + " OR";
return filter;
} else {
filter = "'" + facetKey + "'" + ":'" + facetResults[i];
}
}
} else {
filter = "'" + facetKey + "'" + ": " + facets[facetKey] + "'";
return filter;
}
});

Ignoring the Null results in Jquery

I've a script using navigator's local storage valuesand i've developped a web service that sends me the values, the only issue here is that i dont need it to send me Null results, this is the Function:
function SendNeedHelpLinkTrace() {
var pLinkVirement = sessionStorage.getItem("pClickVirement");
var pLinkCarteBancaire = sessionStorage.getItem("pLinkCarteBancaire");
var pLinkRechargePaiementFactureTelecom = sessionStorage.getItem("pLinkRechargePaiementFactureTelecom");
var pPaiementVignetteImpotTaxe = sessionStorage.getItem("PaiementVignetteImpotTaxe");
var pLinkPaiementFactureEauElectricite = sessionStorage.getItem("pPaiementFactureEauElectricite");
var pLinkServiceFatourati = sessionStorage.getItem("pCatchLinkServiceFatourati");
var pLinkCihExpress = sessionStorage.getItem("pCatchLinkCihExpress");
var pLinkEdocuments = sessionStorage.getItem("pCatchLinkEdocuments");
var lChannelId = "01";
var lServiceId = "900120";
var lClientId = document.getElementById('<%= HiddenClientId.ClientID%>').value;
alert(lClientId);
var lData;
var lCollect;
console.log(lClientId);
lData = pLinkVirement + " | " + pLinkCarteBancaire + " | " + pLinkRechargePaiementFactureTelecom + " | " + pPaiementVignetteImpotTaxe + " | " + pLinkPaiementFactureEauElectricite + " | " + pLinkServiceFatourati + " | " + pLinkCihExpress + " | " + pLinkEdocuments;
console.log(lData);
alert(lData);
lDataCollected = lClientId + ";" + lChannelId + ";" + lServiceId + ";" + lData;
console.log(lDataCollected);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:9097/CatchEvent.asmx/CollectData",
data: JSON.stringify({ "pData": lDataCollected }),
dataType: "json",
async: true,
success: function (data, textStatus) {
if (textStatus == "success") {
alert('success');
}
},
error: function (exception) {
alert('Exeption : ' + exception);
}
});
sessionStorage.clear();
}
the results are like this :
Null || 300123 || 900452 || Null || Null || 26332
what should i do to not show the Null results ?
Given that lDataCollected is an string you can convert it to an array using split() and easily make a filter() excluding the 'Null' values from the array and finally join() to make an string again:
var lDataCollected = 'Null || 300123 || 900452 || Null || Null || 26332';
var result = lDataCollected
.split(' || ')
.filter(function(item) {
return item !== 'Null';
})
.join(' || ');
console.log(result);
Than, the final solution:
function SendNeedHelpLinkTrace() {
var pLinkVirement = sessionStorage.getItem('pClickVirement'),
pLinkCarteBancaire = sessionStorage.getItem('pLinkCarteBancaire'),
pLinkRechargePaiementFactureTelecom = sessionStorage.getItem('pLinkRechargePaiementFactureTelecom'),
pPaiementVignetteImpotTaxe = sessionStorage.getItem('PaiementVignetteImpotTaxe'),
pLinkPaiementFactureEauElectricite = sessionStorage.getItem('pPaiementFactureEauElectricite'),
pLinkServiceFatourati = sessionStorage.getItem('pCatchLinkServiceFatourati'),
pLinkCihExpress = sessionStorage.getItem('pCatchLinkCihExpress'),
pLinkEdocuments = sessionStorage.getItem('pCatchLinkEdocuments'),
lChannelId = '01',
lServiceId = '900120',
lClientId = document.getElementById('<%= HiddenClientId.ClientID%>').value,
lData = pLinkVirement + ' | ' + pLinkCarteBancaire + ' | ' + pLinkRechargePaiementFactureTelecom + ' | ' + pPaiementVignetteImpotTaxe + ' | ' + pLinkPaiementFactureEauElectricite + ' | ' + pLinkServiceFatourati + ' | ' + pLinkCihExpress + ' | ' + pLinkEdocuments,
lDataCollectedString = lClientId + ';' + lChannelId + ';' + lServiceId + ';' + lData,
getLDataCollected = function(str) {
var str
.split(' || ')
.filter(function(item) {
return item !== 'Null';
})
.join(' || ');
};
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'http://localhost:9097/CatchEvent.asmx/CollectData',
data: JSON.stringify({
'pData': getLDataCollected(lDataCollectedString)
}),
dataType: 'json',
async: true,
success: function(data, textStatus) {
if (textStatus === 'success') {
alert('success');
}
},
error: function(exception) {
alert('Exeption:' + exception);
}
});
sessionStorage.clear();
}
As commented by #hindmost, you should create an array of keys that you need to send and loop through them.
But my personal recommendation, send object instead. This way you will know what is empty and what is not.
Sample Code
// map of keys to fetch
var keysToSend = [
'pClickVirement'
'pLinkCarteBancaire'
'pLinkRechargePaiementFactureTelecom'
'PaiementVignetteImpotTaxe'
'pPaiementFactureEauElectricite'
'pCatchLinkServiceFatourati'
'pCatchLinkCihExpress'
'pCatchLinkEdocuments'
]
// Loop to concatinate
var data = keysToSend.reduce(function(p,c){
var _t = sessionStorage.getItem(c);
return isEmpty(_t) ? p : p + ' | ' + _t;
}, '')
// Check validity
function isEmpty(val){
return val === undefined || val === null;
}
Do an OR check
Assuming lData = pLinkVirement + " | " + pLinkCarteBancaire + " | " + pLinkRechargePaiementFactureTelecom produces Null || 300123 || 900452
Since you're getting the data from sessionStorage, the data will be stored as String, hence do a JSON.parse and do the following
NOTE:(incase the string is Null , then do String.toLowerCase() before JSON.parse())
lData = (pLinkVirement || '') + " | " + (pLinkCarteBancaire || '') + " | " + (pLinkRechargePaiementFactureTelecom || '')
Say you got the data pLinkVirement from sessionStorage as Null, do the following
pLinkVirement = pLinkVirement.toLowerCase()
pLinkVirement = JSON.parse(pLinkVirement)
pLinkVirement = (pLinkVirement || '')

JSON parsing in javascript

I'm trying to parse JSON in JavaScript. If my JSON data looks like below, I want to iterate through all the JSON elements that start with "custom" and not with any other string. How do I do this?
{
"fields": {
"custom12": {
value: "dsada"
},
"custom45": {
value: "adsadad"
},
"test12": {
value: "12323"
}
}
}​
var newObject = {}, key;
for(key in data.fields){
if(key.search(/custom/) > -1){
newObject[key] = data.fields[key];
}
}
console.log(newObject);
The following iterates the properties of the fields object and checks whether the property's name contains custom:
var data = yourObjectLiteral, i, current;
for(i in data.fields) {
if(i.indexOf('custom') > -1) {
current = data.fields[i];
// ... your logic ...
}
}
With the json string you provided I'd do it as such:
<script src="json2.js"></script>
<script>
var raw = '{'
+ ' "fields": {'
+ ' "custom12": {'
+ ' "value": "dsada"'
+ ' },'
+ ' "custom45": {'
+ ' "value": "adsadad"'
+ ' },'
+ ' "test12": {'
+ ' "value": "12323"'
+ ' }'
+ ' }'
+ '}';
var data = JSON.parse(raw);
var fields = data.fields;
var message = '';
for (var key in fields) {
if (key.indexOf('custom') === 0) {
message += key + ': ' + fields[key].value + '\n';
}
}
alert(message);
</script>
But, if you can rewrite the incomming message a little it will look simpler.
<script src="json2.js"></script>
<script>
var raw = '{'
+ ' "custom12": "dsada",'
+ ' "custom45": "adsadad",'
+ ' "test12": "12323"'
+ '}';
var fields = JSON.parse(raw);
var message = '';
for (var key in fields) {
if (key.indexOf('custom') === 0) {
message += key + ': ' + fields[key] + '\n';
}
}
alert(message);
</script>

Categories

Resources