Use javascript variable as array index - javascript

I have following code:
var n = 1;
var term = "${abc[n].term}";
console.log("term = " + term);
term seems to be empty, but if I replace
var term = "${abc[n].term}";
by
var term = "${abc[1].term}";
it works.
It looks like jsp is looking for the n property of the deck object, how could I fix it so that n is replaced by its value when I use is as array index ?
Edit:
It seems that it's not a good idea to try mixing JSTL and Javascript, and that if you want to use a javascript variable as array index, you must copy the object to an Array object, like this:
var deck = new Array();
<c:forEach var="v" items="${abc}">
deck.push("${v.term}");
</c:forEach>
var n = 1;
console.log("term = " + deck[n]);

You are not using quotes properly, try this:
var term = "${abc[" + n +"].term}";
"${abc[n].term}" here n is considred as a part of the string not as your variable n. So try concatenating it.

Related

Using map\reduce with nested elements in javascript

I have a search form that allows the user to add as many search terms as they like. When the user enters all of the search terms and their search values and clicks search, a text box will be updated with the search terms. I've got this working with a for loop, but I'm trying to improve my dev skills and am looking for a way to do this with map\filter instead.
Here's the code I'm trying to replace:
var searchTerms = $("#search-form").find(".mdc-layout-grid__inner");
var searchString = "";
for(var i = 0; i < searchTerms.length - 1; i ++)
{
var select = $(searchTerms[i]).find(".select2-selection")[0];
var selectText = $(select).select2('data')[0].text + ":";
var textBox = $(searchTerms[i]).find(".mdc-text-field__input")[0];
searchString = searchString += selectText.replace(/\./g,"").replace(/ /g,"") + textBox.value;
if(i < searchTerms.length - 1)
{
searchString = searchString += " ";
}
}
$("#er-search-input").val(searchString);
Here's a codepen of the current solution.
i'm trying the below, but I get the feeling I'm miles away:
const ret = searchTerms.map((u,i) => [
$($(u[i]).find(".select2-selection")[0]).select2('data')[0].text + ":",
$(u[i]).find(".mdc-text-field__input")[0].value,
]);
My question is, is it possible to do this with map?
Firstly you're repeatedly creating a jQuery object, accessing it by index to get an Element object only to then create another jQuery object from that. Instead of doing this, you can use eq() to get a specific element in a jQuery object by its index.
However if you use map() to loop through the jQuery object then you can avoid that entirely by using this to reference the current element in the iteration. From there you can access the required elements. The use of map() also builds the array for you, so all you need to do is join() the results together to build the required string output.
Finally, note that you can combine the regex expressions in the replace() call by using the | operator, and also \s is more robust than using a whitespace character. Try this:
var $searchTerms = $("#search-form").find(".mdc-layout-grid__inner");
var searchString = $searchTerms.map(function() {
var $searchTerm = $(this);
var selectText = $searchTerm.find('.select2-selection').select2('data')[0].text + ':';
var $textBox = $searchTerm.find('.mdc-text-field__input:first');
return selectText.replace(/\.|\s/g, "") + $textBox.val();
}).get().join(' ');
$("#er-search-input").val(searchString);

Using a variable increment to create new variables in Javascript

It might be a beginner's question, but I can't seem to find an answer on this.
The data it is getting is data out of a JSon file. I want it to loop through all the rows it is seeing. The loop works how it is written below and returns me the info I need with the rest of the code. I am trying to create multiple variables like testVar1, testVar2, testVar3, .... I don't know if it is possible to do it this way, or if I need to find another solution.
var i = 0;
for (var x in data) {
var testVar1 = data[0][1]; // works
var testVar[i] = data[0][1]; // doesn't
i += 1;
}
How can I make the testVar[i] work ?
What is the correct syntax for this?
Your code misses the initialization of your array variable: var testVar = [];.
⋅
⋅
⋅
Anyway, you may want to create those variables in the window object :
for (var i = 0; i <= 2; i++) {
name = 'var' + i;
window[name] = "value: " + i;
}
console.log(var0);
console.log(var1);
console.log(var2);
That way you can keep using the "short" variable name.
You can wrap all those variables in an object.
instead of:
var testVar1 = data[0][1];
Try:
var Wrapper = {};
//inside the for loop:
Wrapper["testVar" + i] = data[0][i];
...and so on.
You'd access them as Wrapper.testVar1 or Wrapper["testVar" + 1].
The problem you're having is pretty simple. You try to declare a variable as an array and in the same statement try to assign assign a value to a certain index. The reason this doesn't work is because the array needs to be defined explicitly first.
var testVar[i] = data[0][1];
Should be replaced with:
var testVar = []; // outside the loop
testVar[i] = data[0][1]; // inside the loop
Resulting in:
var i = 0,
testVar = [],
data = [
['foo', 'bar', 'baz'],
['kaas', 'is', 'baas']
];
for (var x in data) {
var testVar1 = data[0][1];
testVar[i] = data[0][1];
i += 1;
}
console.log('testVar1', testVar1);
console.log('testVar', testVar);
console.log('testVar[0]', testVar[0]);
console.log('testVar[1]', testVar[1]);
If i isn't an integer you should use an object instead. This can be seen in the answer of Tilepaper, although I advise against the use variables starting with a capital letter since they suggest a constant or a class.

Variable name within a loop

I suspect I am making a mistake in a basic JavaScript syntax.
var my_array = new Array(10);
for (var count=0; count<my_array.length; count++) {
var my_array+count = "This is a variable number "+count+".";
document.write(my_array+count);
}
I want the loop to create series of variables that should be called my_array0, my_array1, my_array2, and so on. The code above is how I tried to do that, but it doesn't work. What's the correct way of naming the variable inside the loop?
EDIT: I know I could use my_array[count], but that's not what I'm looking for. What I need is to be able to name a variable inside the loop, using the index as part of the name of the variable.
If you want to set the elements of an array, use the [] syntax:
var my_array = new Array(10);
for (var count=0; count<my_array.length; count++) {
my_array[count] = "This is a variable number "+count+".";
document.write( my_array[count] );
}
Furthermore, when specifying just an element of an array and not the array itself, drop the var in front of it!
This pattern is questionable, and the array seems unnecessary; however, here is one way to do it:
var my_array = new Array(10);
for (var count = 0; count < my_array.length; count++) {
window['my_array' + count] = "This is a variable number " + count + ".";
document.write(window['my_array' + count]);
}
What's the correct way of naming the variable inside the loop? You don't.
If you just want a variable to hold that particular value, just use an ordinary variable. If you want lots of different values, stick it inside an array or object. But that's redundant here since you already have an array, so I'm really not sure what you're trying to achieve.
And if none of the previous answers suits you, you can always use eval()
var varName = 'my_array'
for (var count=0; count<my_array.length; count++) {
eval(varName+count +" = This is a variable number "+count+".");
}
Edit: #Noah Freitas provides a better answer, without using eval().
You're redefining my_array inside the loop, and not accessing the variable correctly either. Try:
var my_array = new Array(10);
for (var count=0; count<my_array.length; count++) {
my_array[count] = "This is a variable number "+count+".";
console.log(my_array[count]);
}
JS Fiddle
You can't execute on the left-hand side of the assignment operator (=), you can only assign. Execution, in javascript, takes place on the right hand side.
var my_array = new Array(10);
var var_hashmap = {}; // create a new object to hold our variables.
for (var count = 0; count < my_array.length; count++) {
var key = "my_array" + count;
var value = "This is a variable number " + count + ".";
var_hashmap[key] = value;
document.write(var_hashmap[key]);
};
var my_array = new Array(10);
for (var count=0; count<my_array.length; count++)
{
eval("var my_array" + count + " = 'This is a variable number'+count+' and the variable name is my_array'+count");
}
alert(my_array0);
alert(my_array1);
alert(my_array2);
alert(my_array3);
alert(my_array4);
alert(my_array5);
alert(my_array6);
alert(my_array7);
alert(my_array8);
alert(my_array9);
http://jsfiddle.net/pe97W/4/
You should use an array.
var myarray = new Array();
myarray[0] = "1";
myarray[1] = "2";
myarray[2] = "3";

Get names and values from array in Javascript

I want to get the values of an array that looks like this:
t = new Object();
t.erg = new Array();
t.erg['random1'] = "something1";
t.erg['random2'] = "something2";
t.erg['random3'] = "something3";
t.erg['random4'] = "something4";
But i want to get the random names and then the values of them through a loop, I can't find a way to do it :/
You would use the other form of the for loop:
for (x in t.erg) {
if (t.erg.hasOwnProperty(x)) {
alert("key is " + x + " value is " + t.erg[x]);
}
}
To get a random value, you could get a random number and append it to the end of the string "random".
Something like this might work:
var randomVal = "random" + Math.floor(Math.random()*4);
To get the the names of something you would use a for in loop, but you are actually creating to objects not an object and an array. Why not use literals like this
t={
erg:{
'random1':'something1',
'random2':'something2'
}
}
for(var x in t.erg){
//in the first round of the loop
//x holds random1
}

How do I access a JSON object using a javascript variable

What I mean by that is say I have JSON data as such:
[{"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}}]
and I want to do something like this:
var x = "ADAM";
alert(data.x.TEST);
var data = [{"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}}],
x = "ADAM";
alert(data[0][x].TEST);
http://jsfiddle.net/n0nick/UWR9y/
Since objects in javascripts are handled just like hashmaps (or associative arrays) you can just do data['adam'].TEST just like you could do data.adam.TEST. If you have a variable index, just go with the [] notation.
var data = [{"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}}]
alert(data[0].ADAM.TEST);
alert(data[0]['ADAM'].TEST)
if you just do
var data = {"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}};
you could access it using data.ADAM.TEST and data['ADAM'].TEST
That won't work as you're setting x to be a string object, no accessing the value from your array:
alert(data[0]["ADAM"].TEST);
var data = [{"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}}],
x = "ADAM";
alert(data[x].TEST);
This is what worked for me. This way you can pass in a variable to the function and avoid repeating you code.
function yourFunction(varName, elementName){
//json GET code setup
document.getElementById(elementName).innerHTML = data[varName].key1 + " " + data.[varName].key2;
}

Categories

Resources