issue with javascript set.has in lwc - javascript

I'm trying to use set.has() in lightning web components and it seems to be not working.
Below is the code snippet..
sStatusToVerify = 'Complete';
var setStatusVals = [...new Set(this.lstAllData.map(obj => obj.sStatus))];
console.log('setStatusVals : ',setStatusVals);
console.log('Contains?? : ' ,setStatusVals.has(sStatusToVerify));
setStatusVals consoles all the values and it contains "Complete". However, the next console is not printed at all. It should ideally print true. Not sure why this is not working.
What is wrong here?

The problem with your solution is , you are converting the set back to array by using the spread operator [... new Set()] and array does not has has method . Hence the issue
var sStatusToVerify = 'Complete';
var arr=[{sStatus:'Complete'},{sStatus:'Start'},{sStatus:'InProgress'}];
var setStatusVals = new Set(arr.map(obj => obj.sStatus));
console.log(setStatusVals.has(sStatusToVerify));

Related

Why isn't my bulk variable assignment working as expected?

I am trying to make it small (short), but it is not happening, please tell me where I am wrong. And where I am wrong, you correct there...
var set1 = document.querySelector(".get1");
var set2 = document.querySelector(".get2");
var set3 = document.querySelector(".get3");
var set4 = document.querySelector(".get4");
to..
var ("[set1],[set2],[set3],[set4]")
= document.querySelector("[.get1],[.get2],[.get3],[.get4]")
but it's not work
First code is work very well but the second code which is a shortened form of the first code is not working
You will have to use .map() and destrcutring to transform your given array and then assign it to individual values. You can do this:
let [var1,var2,var3,var4] =
['.get1','.get2','.get3','.get4'].map(x => document.querySelector(x));
But as mentioned your code is fine the way it is. It is simpler and easier to understand.

What is a PoliglotMap in GraalVM?

I am working with the org.graalvm.polyglot script engine in my Java11 project to evaluate a JavaScript.
The script to be evaluated returns a JavaScript array with two entries.
...
var result={};
result.isValid=false;
result.errorMessage = new Array();
result.errorMessage[0]='Somehing go wrong!';
result.errorMessage[1]='Somehingelse go wrong!';
....
In my java code I try to evaluate the result object:
Value resultValue = context.getBindings(languageId).getMember("result");
In my Eclipse Debugger I can see that I receive a PolyglotMap containing the expected values:
I can iterate over that map to get the values with a code like this:
...
try {
mapResult = resultValue.as(Map.class);
} catch (ClassCastException | IllegalStateException | PolyglotException e) {
logger.warning("Unable to convert result object");
return null;
}
Iterator it = mapResult.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
String itemName = pair.getKey().toString();
Object itemObject = pair.getValue();
...
In this way I am able to extract the boolean 'isValid'. But with the object 'errorMessage' I struggle.
Inspecting the Object again within the Eclipse Debugger it looks like this:
If I test this object it is an instanceOf Map. But I am unable to get any of the values out of this object.
Can anybody help me to understand what exactly this object represents and how I can extract the both values 'Someting go wrong!' and 'Sometingelse go wrong!' ?
When I iterate over this second map it seems to be empty - even if the debugger shows me the correct values.
I'm not 100% sure why as(Map.class) behaves that way, it might be worth creating an issue on github to figure it out: github.com/oracle/graal
But if you access the values using the API without converting to a Map it would work as you expect:
var errorMessage = resultValue.getMember("errorMessage");
errorMessage.hasArrayElements(); // true
var _0th = errorMessage.getArrayElement(0);
var _1th = errorMessage.getArrayElement(1);
You can also convert the polyglotMap to Value and then do it:
val errorMessage = context.asValue(itemObject);
errorMessage.hasArrayElements(); // true
errorMessage.getArrayElement(0);
PolyglotMap of course has the get method. And the Value javadoc says that:
Map.class is supported if the value has Value.hasHashEntries() hash entries}, members or array elements. The returned map can be safely cast to Map. For value with members the key type is String. For value with array elements the key type is Long.
Can you try getting them with the Long keys?
There might be something obvious I'm missing, so in any case it's better to raise an issue on GitHub.

Dynamically create a TW object in IBM BPM

I am using IBM BPM 8.6
I have an input string as follows:
"\"RECORD_CONTACT\":\"Maram\" , \"DRUG\":\"Panadol\"
In a script on server side, I want to dynamically create a business object like this:
tw.local.recordContact = Maram;
tw.local.drug = Panadol;
How can I dynamically create the business object?
There are a few problems with your request. The first is that you are not creating a business object, you are creating variables. In IBM BPM the variables have to be declared at design time or you will get an error, so invoking attempting to call something like -
tw.local.myVariable = 'Bob';
Will throw an exception if tw.local.myVariable has not been declared. Base on your other question you asked here (link), I'm going to assume you actually have an ANY variable declared called "return" so that
tw.local.return.myVariable = 'Bob'
will work. Given that I based on Sven's answer I think something like the following will work (you will need to validate)
var str = "\"RECORD_CONTACT\":\"Maram\" , \"DRUG\":\"Panadol\"";
var jsonStr = "{" + str.replace(/\\\"/g,'\"') + "}";
var tempValue = JSON.parse(jsonStr);
var keyArray = Object.keys(tempValue);
var valueArray = Object.values(tempValue);
for(var keyCount=0; keyCount<keyArray.length; keyCount++{
var evalString = "tw.local.return."+keyArray[keyCount]+"="+valueArray[keyCount];
eval(evalString);
}
I'll note that doing this is a very bad idea as it would be very brittle code and that using eval() in this manner opens you up to all sorts of possible exploits. It will also fail badly if the value for one of the keys is not a simple type.
-Andrew Paier
One should know what you are going to do with dynamically created Business Objects (BO) to answer you better. Like a very generic way would be - creating JSON object instead of BO.
But if you want to stick with BO then this is only possible when you know all the BO structure (schema) beforehand during design time.
var str = "\"RECORD_CONTACT\":\"Maram\" , \"DRUG\":\"Panadol\"";
vat objArray = str.split("reg ex to split each object string")
foreach (obj in objArray ){
if(obj.indexOf( "RECORD_CONTACT")!=-1)
tw.local.recordContact = new tw.object.RECORD_CONTACT();
//below goes code get value of each attribute of BPM from string
}
else if(obj.indexOf( "DRUG")!=-1){
//similar code to create BO DRUG
}
Don't forget to create BO before using those :)

Array has only 4 elements but it shows like it has 5 elements even after removing empty elements

I have an array with 4 elements and in one scenario I want to pop one element from the array. But after pop array gives the same result as before.
I have checked in the console window and there I have find a different behavior like array length is 4 and it shows like it has 5 elements.
I have tried to remove the empty elements also but still the same issue is coming .
var brudcrumbDataArray=JSON.parse(brudcrumbDataString);
brudcrumbDataArray = brudcrumbDataArray.filter(function(n){ return n != undefined });
console.log(brudcrumbDataArray)
brudcrumbDataArray.pop();
console.log(brudcrumbDataArray)
Her is the array :
[{"name":"Dashboard","url":"","path":"","class":"icon-home2 position-left","type":"MainMenu","queryParams":""},{"name":"Main","url":"#/dashboard","path":"/dashboard","class":"","type":"SubMenu","queryParams":""},{"name":"Sub Accounts","url":"#/account/customers","path":"/account/customers","class":"","type":"SubMenu","queryParams":""},{"name":"End Users","url":"#/account/endusers","path":"/account/endusers","class":"","type":"SubMenu","queryParams":""},{"name":"Profile","url":"#/user-dashboard","path":"/user-dashboard","class":"","type":"SubMenu","queryParams":""}]
After pop also array gives the same data and same length. Can someone help me to solve this issue ?
Snippet, check your console to see the problem:
var brudcrumbDataString =`[{"name":"Dashboard","url":"","path":"","class":"icon-home2 position-left","type":"MainMenu","queryParams":""},{"name":"Main","url":"#/dashboard","path":"/dashboard","class":"","type":"SubMenu","queryParams":""},{"name":"Sub Accounts","url":"#/account/customers","path":"/account/customers","class":"","type":"SubMenu","queryParams":""},{"name":"End Users","url":"#/account/endusers","path":"/account/endusers","class":"","type":"SubMenu","queryParams":""},{"name":"Profile","url":"#/user-dashboard","path":"/user-dashboard","class":"","type":"SubMenu","queryParams":""}]`;
var brudcrumbDataArray=JSON.parse(brudcrumbDataString);
brudcrumbDataArray = brudcrumbDataArray.filter(function(n){ return n != undefined });
console.log(brudcrumbDataArray)
brudcrumbDataArray.pop();
console.log(brudcrumbDataArray)
A result on the console seems to be correct. Both the logs on the console window are showing the result after the operation. Why is the first log showing a result in it? because, in javascript, complex objects get stored by reference, that's why your first log does show a result in it too.
Store by reference? what does it mean? : https://docstore.mik.ua/orelly/webprog/jscript/ch04_04.htm
Try below one,
var brudcrumbDataString =`[{"name":"Dashboard","url":"","path":"","class":"icon-home2 position-left","type":"MainMenu","queryParams":""},{"name":"Main","url":"#/dashboard","path":"/dashboard","class":"","type":"SubMenu","queryParams":""},{"name":"Sub Accounts","url":"#/account/customers","path":"/account/customers","class":"","type":"SubMenu","queryParams":""},{"name":"End Users","url":"#/account/endusers","path":"/account/endusers","class":"","type":"SubMenu","queryParams":""},{"name":"Profile","url":"#/user-dashboard","path":"/user-dashboard","class":"","type":"SubMenu","queryParams":""}]`;
var brudcrumbDataArray=JSON.parse(brudcrumbDataString);
brudcrumbDataArray = brudcrumbDataArray.filter(function(n){ return n != undefined });
console.log(JSON.parse(JSON.stringify(brudcrumbDataArray)))
brudcrumbDataArray.pop();
console.log(JSON.parse(JSON.stringify(brudcrumbDataArray)))
Look closely here, we are doing deep data copy with using JSON operations, by surrounding object in JSON.parse(JSON.stringify( )) and it won't point to reference anymore now.
And log will be more clear as below,
it showing because the reference to the same object so when you pop last element the object get modified and shows the length as 4 so the first consoled object also get updated.
var brudcrumbDataArray = [{"name":"Dashboard","url":"","path":"","class":"icon-home2 position-left","type":"MainMenu","queryParams":""},{"name":"Main","url":"#/dashboard","path":"/dashboard","class":"","type":"SubMenu","queryParams":""},{"name":"Sub Accounts","url":"#/account/customers","path":"/account/customers","class":"","type":"SubMenu","queryParams":""},{"name":"End Users","url":"#/account/endusers","path":"/account/endusers","class":"","type":"SubMenu","queryParams":""},{"name":"Profile","url":"#/user-dashboard","path":"/user-dashboard","class":"","type":"SubMenu","queryParams":""}]
//var brudcrumbDataArray=JSON.parse(brudcrumbDataString);
var newBrudcrumbDataArray = brudcrumbDataArray.filter(function(n){ return n != undefined });
console.log(brudcrumbDataArray)
newBrudcrumbDataArray.pop();
console.log(newBrudcrumbDataArray)

Shift is not a function in javascript

I have multiple tables(with same structure)in my html. They are in tabs. I am creating tabs dynamically and i want to send those table data to the mysql database. So i wanted to get those data using javascript. I am correctly created TableData1,TableData2.... arrays using for loop. Problem is I cannot increment TableData here ('TableData'+i).shift(); . I am getting an error. I want to create TableData1.shift(),TableData2.shift().....
function myDataSendFunction(){
var i;
for(i = 1; i <= array_size; i++){
eval("var TableData"+i+"=[];");
$('#mytable'+i+ ' tr').each(function(row, tr){
('TableData'+i)[row]={
"colum1" : $(tr).find('td:eq(1)').text()
, "colum2" :$(tr).find('td:eq(2)').text()
, "colum3" : $(tr).find('td:eq(3)').text()
, "colum4" : $(tr).find('td:eq(4)').text()
, "colum5" : $(tr).find('td:eq(5)').text()
, "colum6" : $(tr).find('td:eq(6)').text()
, "colum7" : $(tr).find('td:eq(7)').text()
, "colum8" : $(tr).find('td:eq(8)').text()
}
});
('TableData'+i).shift();
}
}
I am getting this error.
Uncaught TypeError: ("TableData" + i).shift is not a function
at myDataSendFunction (<anonymous>:25:25)
at HTMLInputElement.onclick (create.php:1)
It's clear that you are very new to this, so I'm going to show you first and then explain second.
function myDataSendFunction(){
var i,
TableData = [];
for(i = 1; i <= array_size; i++){
TableData[i] = [];
$('#mytable' + i + ' tr').each(function(row, tr){
TableData[i][row]={
"colum1" : $(tr).find('td:eq(1)').text()
, "colum2" : $(tr).find('td:eq(2)').text()
, "colum3" : $(tr).find('td:eq(3)').text()
, "colum4" : $(tr).find('td:eq(4)').text()
, "colum5" : $(tr).find('td:eq(5)').text()
, "colum6" : $(tr).find('td:eq(6)').text()
, "colum7" : $(tr).find('td:eq(7)').text()
, "colum8" : $(tr).find('td:eq(8)').text()
};
});
TableData[i].shift();
}
}
Base on your comment:
what should i do then?? I tried with TableData array, then problem occurs in here TableData[i][row] with Uncaught TypeError: Cannot set property '0' of undefined
Your troubles revolve around setting properties on variables that haven't been defined. You must define TableData before attempting to assign a property.
Once TableData is "initialized" to an array (var TableData = []), you can set properties on TableData. But you cannot immediately set properties on properties of TableData. For example, you cannot jump directly to TableData[i][row]. You must first set TableData[i] to an array (TableData[i] = []), and then you can set TableData[i][row] to some value.
By trying to solve that problem with eval, you ran into a whole new world of problems. Try to avoid eval... it's a very complicated beast that tends to cause a lot of confusion and pain.
It may be helpful to review MDN's Working with objects documentation to better understand what's going on with JavaScript's array and objects.
Apparently your element selection is the mistake you have done. Without using a for loop by hard coding an array_size you could have easily
select all the tables at once using a common property like class. You will get an array with table objects.
Iterate the table objects array.
Inside the loop select all the rows of each table and put them into another loop to extract data and create the data array which you sends to the DB.
Find my sample implementation here.
Please do remember that when you're planning to use arrays, stick to the arrays rather than moving back and forth between strings and arrays. It will cause you problems like what you have already came across and unnecessary dirty code.

Categories