Nested object with square bracket notation in JavaScript - javascript

I'm trying to achieve the following:
this.inputs[options.el.find('form').attr('class')] = {};
this.inputs[options.el.find('form').attr('class')][options.elements[x].selector] = false;
However, I'm unable to do the above without a syntax error!
Any ideas how I could achieve this Object structure?

That syntax looks legal, but these long one liners aren't doing anyone any favors. Break it apart a bit so you can find where it's failing.
var className = options.el.find('form').attr('class');
var selector = options.elements[x].selector;
this.inputs[className] = {};
this.inputs[className][selector] = false;

The index to an object should always be a string:
var obj = {
a: 2;
}
obj.a = 3; //a is 3 now
obj['a'] = 4;//a is 4 now
You said options.elements[x].selector is input[name="username"] so I guess in this line:
this.inputs[options.el.find('form').attr('class')][options.elements[x].selector] = false;
What you are really trying to do is:
this.inputs[options.el.find('form').attr('class')]['username'] = false;
So you can do like this:
var sel = options.elements[x].selector;
console.log( 'sel is ' + sel );
this.inputs[options.el.find('form').attr('class')][sel] = false;
Make sure that sel is a string. You may want to try
var sel = options.elements[x].selector.value;
The .value bit retrieves the text from inside an input element.

Related

JS: Check Query String for GET variables that are not in an array?

Let's say I have an address of:
www.example.com/index.php?a=1&b=2&c=3
I want to enter that into an input field like this (value would obviously initially be blank):
<input id="my-input-field" value="www.example.com/index.php?a=1&b=2&c=3">
Then I want JS to parse everything after the ?, take all of the queries ("a", "b", "c") and see if they exist in an array().
Then I want to display a message stating that some of the items in the given URL were missing - but that's the easy part.
The part that I'm having trouble figuring out is: how to break down the URL and only find the first part of each query?
I understand how to strip everything before the question mark (including the question mark):
var str = "www.example.com/index.php?a=1&b=2&c=3";
str = str.substring(str.indexOf("?") + 1);
alert(str);
Fiddle: http://jsfiddle.net/xx3fwhvv/
This returns: a=1&b=2&c=3
The next step could be to split the string up per each &?
var str = "a=1&b=2&c=3";
str = str.split("&");
alert(str);
Fiddle: http://jsfiddle.net/3Lo24byo/
This returns: a=1,b=2,c=3
We can then remove everything after the ='s sign like this:
var str = 'a=1';
str = str.substring(0, str.indexOf('='));
alert(str);
Fiddle: http://jsfiddle.net/vfzvu5mh/
This results in: a
The thing now is how do I loop through the array and do this for each item? That would be the step I need to take.
Then I need to have an array like:
var myArray = array('a','c','d');
In the above array, cross checking the array that we created above to see if any of the values match up should return b as not matching up, as it's not in myArray.
This is where I'm stuck. Any help is appreciated. I'm not very good with JS but I've been working at this trying to figure it out.
All together so far, the code would look something like this:
var str = "www.example.com/index.php?a=1&b=2&c=3";
newStr = str.substring(str.indexOf("?") + 1);
strArray = newStr.split("&");
i = 1;
for {
newStrArray = strArray[i].substring(0, strArray[i].indexOf('='));
i++;
}
The above doesn't work for me, but something like that any way.
EDIT (I'll be actively editing this part until the question is answered):
var str = "www.example.com/index.php?a=1&b=2&c=3";
var newStr = str.substring(str.indexOf("?") + 1);
var myStringArray = newStr.split("&");
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
myStringArray = myStringArray[i].substring(0, myStringArray[i].indexOf('='));
alert(myStringArray[i]);
}
Current Fiddle: https://jsfiddle.net/03ho0nbz/
First off, you're overwriting your array with the result of a substring:
myStringArray = myStringArray[i].substring(0, myStringArray[i].indexOf('='));
myStringArray receives the results of the substring, turning it into a string.
To compare myArray with otherArray and see if an element not exists in myArray you can use the indexOf() function:
var myArray = ['a', 'c', 'd'];
var otherArray = ['a', 'b', 'c'];
for(var i=0;i<otherArray.length;i++) {
if(myArray.indexOf(otherArray[i]) === -1) {
console.log('myArray does not have', otherArray[i]); // myArray does not have b
}
}
Going by your example this would create a loop looking something like:
var str = "www.example.com/index.php?a=1&b=2&c=3";
var newStr = str.substring(str.indexOf("?") + 1);
var myStringArray = newStr.split("&");
var myArray = ['a', 'c', 'd'];
for (var i = 0; i < myStringArray.length; i++) {
var eqIndex = myStringArray[i].indexOf('=');
if(eqIndex !== -1) {
var key = myStringArray[i].substring(0, eqIndex);
if(myArray.indexOf(key) === -1) {
alert(key, "not in myArray!");
}
}
}
Note that this way of writing JS is fine for learning practices, but if you intend to use JS in a professional setting, please read up on some JS good practices.
What i would do is to fiddle around with JS like you're doing, try and see if you can buy some JS good practices books and also look at how popular frameworks solve things. For professional purpose it's almost always a good idea to use a framework that's well maintained and supported. For example if you would use underscore in this case you could do something like:
var paramKeys = _.chain("a=1&b=2&c=3".split('&')).map(function(params) {
var p = params.split('=');
return p[0];
}).value();
_.difference(paramKeys, ['a', 'c', 'd']) // "b"
#mattroberts33 I am unable to understand why you are checking first parameter in the url, is there anything deference from www.example.com/index.php?a=1&b=2&c=3 to www.example.com/index.php?b=2&a=1&c=3. I would encourage read parameters based on the keys instead of index. In any url query parameters might jumbled.
Below method will return parameter by passing key and url to the method:
var getParameterByName = function (name, url) {
name = name.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
if (url) {
var results = regex.exec(url);
} else {
var results = regex.exec(location.search);
}
return results == null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));};
If you still wants to get based on index we can modify above method, But that is not encouraging.

Javascript: How to re-arrange content display of text field?

I have a text field (not a date field) who contain simply a value such "2013-08-27" and my goal would be to reverse the order and get "27-08-2013". So is matter to re-arrange the content but I don't have enough javascript knowledge. I tried using some "date" variable but without success much probably because my field is not a date field.
The html related to the field look like this:
<input type="text" value="2013-08-27" name="my_field" id="my-field" readonly="">
If you can give me an example of code based of this:
var my_field = document.getElementById('my_field');
thank
PS: I precise I don't have access to html of this field because is located to a remote server. I can only interact by adding code in a JS file planned for that. The field have also a "readonly" property because is not planned for be modified.
This code should do the trick:
var revert = function(str) {
var parts = str.split("-");
var newArr = [];
for(var i=parts.length-1; p=parts[i]; i--) {
newArr.push(p);
}
return newArr.join("-");
}
var replaceValueInInputField = function(id) {
var field = document.getElementById(id);
field.value = revert(field.value);
}
var replaceValueInDomNode = function(id) {
var el = document.getElementById(id);
var value = el.innerHTML, newValue = '';
var matches = value.match(/(\d{4})-(\d{2})\-(\d{2})/g);
for(var i=0; m=matches[i]; i++) {
value = value.replace(m, revert(m));
}
el.innerHTML = value;
}
replaceValueInInputField("my-field");
replaceValueInDomNode("my-field2");
jsfiddle http://jsfiddle.net/qtDjF/2/
split('-') will return an array of number strings
reverse() will order array backwards
join("-") will join array back with '-' symbol
var my_field_value = document.getElementById('my_field').value;
my_field_value.split('-').reverse().join("-");
You can use the split function.
var my_field = document.getElementById('my_field').split("-");
the var my_field will be an array of string like : "YYYY,mm,dd"
and then you can re-arrange it in the order you want.
Try this
var date = document.getElementById("my-field").value;
//alert(date);
var sp = date.split("-");
alert(sp[2]+"-"+sp[1]+"-"+sp[0]);
With Jquery
var parts =$('#my-field').val().split("-");
$('#my-field').val(parts[2]+"-"+parts[1]+"-"+parts[0]);
Simple regex:
var res;
test.replace(/(\d\d\d\d)-(\d\d)-(\d\d)/,function(all,a,b,c){res=c+"-"+b+"-"+a;});
JSFiddle: http://jsfiddle.net/dzdA7/8/
You could try splitting the string into array and inverting it's items in a loop:
var my_field = document.getElementById('my_field').value.split("-"),
length = my_field.length,
date = [];
for(i = length - 1; i >= 0; i--){
date.push(my_field[i]);
}
console.log(date.toString().replace(/,/g,"-"));

don't get return associative array in javascript

When i create associate array in javascript, i got a problem like that.
I want to get the value by using field name as key, but i just only got undefined.
What should i do to get value by key or which way is good approach for it.
Here is my code
function getFields(pVal){
var tmpObj = {};
str = pVal.split(",");
for(i=0;i<str.length;i++){
tmpVal = str[i].split(":");
tmpObj[tmpVal[0]] = tmpVal[1];
}
return tmpObj;
}
function JustTest(){
var fields = {};
fields = getFields("'Code':'PRJ001','Name':'Project 01'");
alert(fields['Code']);
}
Because the key is 'Code', not Code, note the single quote ', you need do alert(fields["'Code'"]);
PS: Please add ; at the end of statement, it is bad practice to omit them.
I have re-factor the code, just try this:
function getFields(pVal) {
var tmpObj = {};
var str = pVal.split(",");
for (var i = 0; i < str.length; i++) {
var tmpVal = str[i].split(":");
tmpObj[tmpVal[0]] = tmpVal[1];
}
return tmpObj;
}
function JustTest() {
var fields = { };
fields = getFields("'Code':'PRJ001','Name':'Project 01'");
alert(fields["'Code'"]);
}
if you have question please comment below about code, thanks

Javascript / DOM, parsing Key/Value string

I send a string from a server to the Firefox Browser in the format below:
"KEY:a1 VAL:123.45"
And this string can contain many such records.
Here is the code I have written:
var e;
var reply = request.responseText;
var txt = "", tab, key = "", val = "";
var x = reply.getElementsByTagName("KEY:");
for(i = 0; i < x.length; i++)
{
txt = x[i].childNodes[0].nodeValue; // "KEY:%c%c VAL:%.2F"
tab = txt.split(":");
key = "table_" + tab[1].substring(0,1);
val = tab[2];
e = document.getElementById(key);
e.innerHTML = val;
e.style.display = "block";
}
val displays "KEY:a1 VAL:123.45" instead of the expected "123.45" (and of course the key variable is also wrong, not matching a table cell, just picking the first one in the table).
I don't even know how to display the key and val values (document.write() and alert() do nothing and I don't see how to trace this code in Firefox).
Any idea, tip, correction, or code example is welcome but please don't recommend using any library, I want to do it with little code.
EDIT: from the two comments, I understand that there are two distinct ways to proceed: either using DOM objects and HTML tags, or using 'strings'. I would prefer to keep using the format above, so please guide me to a 'string' solution. Thanks!
You can use a simple regular expression to extract the information from the string:
var value = "KEY:a1 VAL:123.45"​,
pattern = /KEY:(\S+) VAL:(.+)$/g;
var result = pattern.exec(value);
// result[1] == 'a1'
// result[2] == '123.45'
In your case, you'd use request.responseText instead of value.

Parse values out of paramaterized strings in javascript

Say I have a string, such as:
var map = "/directory/:id/thumbnails/:size";
And I want to use that to map against another string (essentially, the same thing that Rails uses to define Routes), such as:
var str = "/directory/10/thumbnails/large";
I would like to "compare" the two strings, and return a Key-Value Pair or JSON Object that represents the parts of str that map to map, which in my example above, would look like:
obj = {
'id' : '10',
'size' : 'large'
}
Would this be a good fit for JavaScript Regex? Can anyone help me?
I found it easier to just write the code for this than to explain :)
var map = "/directory/:id/thumbnails/:size";
var str = "/directory/10/thumbnails/large";
var obj = {};
var mapArr = map.split('/');
var strArr = str.split('/');
if (mapArr.length != strArr.length) return false;
for (var i = 0; i < mapArr.length; i++)
{
var m = mapArr[i];
var s = strArr[i];
if (m.indexOf(":") != 0) continue;
m = m.substring(1);
obj[m] = s;
document.write(m + " = ");
document.write(obj[m]);
document.write("<br/>");
}
You can also see it in action here => http://jsfiddle.net/5qFkb/
Do ask if you have any questions, but the code should be self-explanatory. Also be aware that there is no usual null checking and stuff I'd usually put in - this is just meant as a quick and dirty proof of concept.
Oh and in case it wasn't clear from my answer; no, I wouldn't use regex, because then I'd have two problems instead of one.

Categories

Resources