ExtJs - best way to check if Ext.Array is empty? - javascript

In ExtJS, using an Ext.Array (after using Ext.Array.difference), I get a resulting array and would like to know the best way to check if the array is empty?
I did use theArray.length as one could do in javascript, but I'm wondering if there is a better way/faster to acheive that? (At first I thought that isEmpty would help but it seems to be working on object, not array)

You can easily add this to the Array prototype like this:
Array.prototype.isEmpty = function(){
return !this.length;
};
var a = ['a','b','c','d'];
var b = ['b','d','f','h'];
var c = Ext.Array.difference(a,b);
var d = [];
console.log(c.isEmpty(), d.isEmpty());
Hope it helps :)

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.

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 :)

Store jQuery objects in an array/object

I want to create a JS array that contains jQuery objects like this:
var oFormFields = new Object;
oFormFields.label = $(document.createElement('label'));
oFormFields.input = $(document.createElement('input'));
Since this crashes my code, i expect this is not possible. Any alternatives? This is my simplified version, I want to include some other properties so I'm able to re-use this in my code when building dynamic forms.
EDIT: Seemed this did work after all... what I wanted to do, was something like this:
var oFormFields = new Object;
oFormFields.name_field.label = $(document.createElement('label')).addClass('nam_field');
oFormFields.name_field.input = $(document.createElement('input')).addClass('nam_field');
This does break my code. I'm pretty new to jQuery, coming from a PHP background I'm having some troubles adjusting to the correct way to work with arrays / objects.
Just use it like this:
var oFormFields = {
label: $('<label />'),
input: $('<input />')
};
You can create the element directly using jQuery. Furthermore, as mentioned in the comments, you should prefer the object literal notation over the new syntax.
var arr = [];
var oFormFields = {};
oFormFields.label = $('<label/>');
oFormFields.input = $('<input/>');
arr.push(oFormFields);
.........

Dynamically making a Javascript array from loop

I know there are a lot of questions about this, but I can't find the solution to my problem and have been on it for a while now. I have two sets of input fields with the same name, one for product codes, and one for product names. These input fields can be taken away and added to the DOM by the user so there can be multiple:
Here is what I have so far, although this saves it so there all the codes are in one array, and all the names in another:
var updatedContent = [];
var varCode = {};
var varName = {};
$('.productVariationWrap.edit input[name="varVariationCode[]"]')
.each(function(i, vali){
varCode[i] = $(this).val();
});
$('.productVariationWrap.edit input[name="varVariationName[]"]')
.each(function(i1, vali1){
varName[i1] = $(this).val();
});
updatedContent.push(varCode);
updatedContent.push(varName);
I am trying to get it so the name and code go into the same array. i.e. the code is the key of the K = V pair?
Basically so I can loop through a final array and have the code and associated name easily accessible.
I can do this in PHP quite easily but no luck in javascript.
EDIT
I want the array to look like:
[
[code1, name1],
[code2, name2],
[code3, name3]
];
So after I can do a loop and for each of the arrays inside the master array, I can do something with the key (code1 for example) and the associated value (name1 for example). Does this make sense? Its kind of like a multi-dimensional array, although some people may argue against the validity of that statement when it comes to Javascript.
I think it's better for you to create an object that way you can access the key/value pairs later without having to loop if you don't want to:
var $codes = $('.productVariationWrap.edit input[name="varVariationCode[]"]'),
$names = $('.productVariationWrap.edit input[name="varVariationName[]"]'),
updatedContent = {};
for (var i = 0, il = $codes.length; i < il; i++) {
updatedContent[$codes.get(i).value] = $names.get(i).value;
}
Now for example, updatedContent.code1 == name1, and you can loop through the object if you want:
for (var k in updatedContent) {
// k == code
// updatedContent[k] == name
}
Using two loops is probably not optimal. It would be better to use a single loop that collected all the items, whether code or name, and then assembled them together.
Another issue: your selectors look a little funny to me. You said that there can be multiple of these controls in the page, but it is not correct for controls to have duplicate names unless they are mutually exclusive radio buttons/checkboxes--unless each pair of inputs is inside its own ancestor <form>? More detail on this would help me provide a better answer.
And a note: in your code you instantiated the varCode and varName variables as objects {}, but then use them like arrays []. Is that what you intended? When I first answered you, i was distracted by the "final output should look like this array" and missed that you wanted key = value pairs in an object. If you really meant what you said about the final result being nested arrays, then, the smallest modification you could make to your code to make it work as is would look like this:
var updatedContent = [];
$('.productVariationWrap.edit input[name="varVariationCode[]"]')
.each(function(i, vali){
updatedContent[i] = [$(this).val()]; //make it an array
});
$('.productVariationWrap.edit input[name="varVariationName[]"]')
.each(function(i1, vali1){
updatedContent[i1].push($(this).val()); //push 2nd value into the array
});
But since you wanted your Code to be unique indexes into the Name values, then we need to use an object instead of an array, with the Code the key the the Name the value:
var updatedContent = {},
w = $('.productVariationWrap.edit'),
codes = w.find('input[name="varVariationCode[]"]'),
names = w.find('input[name="varVariationName[]"]');
for (var i = codes.length - 1; i >= 0; i -= 1) {
updatedContent[codes.get(i).val()] = names.get(i).val();
});
And please note that this will produce an object, and the notation will look like this:
{
'code1': 'name1',
'code2': 'name2',
'code3': 'name3'
};
Now you can use the updatedContent object like so:
var code;
for (code in updatedContent) {
console.log(code, updatedContent[code]); //each code and name pair
}
Last of all, it seems a little brittle to rely on the Code and Name inputs to be returned in the separate jQuery objects in the same order. Some way to be sure you are correlating the right Code with the right Name seems important to me--even if the way you're doing it now works correctly, who's to say a future revision to the page layout wouldn't break something? I simply prefer explicit correlation instead of relying on page element order, but you may not feel the need for such surety.
I don't like the way to solve it with two loops
var updatedContent = []
$('.productVariationWrap.edit').each(function(i, vali){
var $this = $(this)
, tuple = [$this.find('input[name="varVariationCode[]"]').val()
, $this.find('input[name="varVariationName[]"]').val()]
updatedContent.push(tuple)
});

Convert List to Structure Using Javascript or JQuery

I've apologize if this is a trivial task, and I've also been googling and searching high and low for some solution I can get my head around but so far no dice. So anyways....
I have this:
var myList = "key1,value1,key2,value2"
And I want to populate a struct with this string so I can reference it like this:
alert(myList.key1) // displays value1
Thoughts? There's probably some way to do this with JQuery's .each() perhaps? I'm seriously lost either way! Maybe just because it's really late and I've been stumbling through familiarizing myself with JS and JQuery again after a long hiatus. Any help is appreciated!
Assuming you never have commas in the values, you could start by using split:
var parts = myList.split(",");// ["key1", "value1", ...]
From there you can just use a simple loop:
var obj = {};
for (var i = 0; i < parts.length; i+=2) obj[parts[i]] = parts[i + 1];
As this answer points out, you can also write the loop like this:
var obj = {};
while (parts.length) obj[parts.shift()] = parts.shift();
This is a neat way to write this, but behaves differently: after this loop, parts will be empty.
String.replace method is your first choice when it comes to string parsing tasks
var myList = "key1,value1,key2,value2"
var result = {}
myList.replace(/(\w+),(\w+)/g, function($0, $1, $2) {
result[$1] = $2
})

Categories