Select element from json dynamically - javascript

I have a an associative array in php that i parse to get json from it (json_encode) then i store the result in a javascript var
var myArray = <?php print json_encode($phpArray); ?>;
Now whene the user hit a button i should choose another element from the array dynamically, for example, i chose a random first element :
var an_element = myArray.a2.link;
-'a2' is an array in the main array
-'link' is an element in the a2 array.
So now whene the user hit my button, i want to choose a random other array id (for example a5, a9, etc.)
I tried this :
var randomnumber=Math.floor(Math.random()*101); // choose random number
var newRandomArrayID= "a"+randomnumber;
an_element = myArray.newRandomArrayID.link;
It doesn't works, it says myArray.newRandomArrayID is undefined.
Anyone can help?
Thank you

You need to use [] indexing to find properties by name:
an_element = myArray[newRandomArrayID].link;
Otherwise JS is looking for a property actually called newRandomArrayID on myArray rather than using the value of the variable to lookup the property.

Related

Assigning Array Value Gives Undefined Key

I have a multidimensional array of 100 trucks. Each truck holds several boxes.
I insert the first box of each truck by splicing from the box array to the truck array:
removed = allBoxes.splice(x, 1)[0];
trucks[i] = {0: removed};
Because I know it's the first box, I can put the {0:. But to add the next box, I want it to be dynamic.
I can insert it at the right place, but the key is undefined instead of 1 for the next box.
removed = allBoxes.splice(x, 1)[0];
trucks[i][trucks[i].length] = removed;
You can see the results here: Instead of undefined:, can it say 1? Whenever I try to add a variable in the array, it just writes out the variable string, not the value.
As #JordanBurnett mentioned, it wasn't an array. I had to count how many objects were in the array. Using the below code (from this question) gave the desired result:
var size = Object.keys(trucks[i]).length;
trucks[i][size] = removed;

Why won't append row work with array?

I am trying to insert a row to the bottom of a sheet, but instead of my values I see text similar to what happens when you try to print an array in Java. I checked to see if the array is made correctly with logger and it has the values I want.
var name = e.range.getRow() + SpreadsheetApp.getActiveSpreadsheet().getName();
var array = e.range.getValues().concat(name);
Logger.log(array.toString());
masterSheet.appendRow(array);
array contains a timestamp, string1, string2, and finally the name I concatenated. Instead I get something like [Ljava.lang.Object;#7dch7145
This is because appendRow() is looking for array[] not array[][].
If you attempt to append:
var array = [[1,2,3],"some string"]
It will show up as the following as it is trying to get the entire contents of the first position of the array in a single cell. It does this by returning a string of the array object which turns out to be the native code identifier.
[Ljava.lang.Object;#32dba1e2 | some string
You can append the contents of array by appending its individual members such as
ss.appendRow(array[0])
Would append
1 | 2 | 3
It looks like a problem with your use of getValues() which returns a two-dimensional array and needs to be accessed as such.
GAS API Reference: getValues()
Return
Object[][] — a two-dimensional array of values
I believe this edit to setting your var array should do the trick, assuming your data range is for a single row (index 0 will be the first row, otherwise just change the index to the row you want):
var array = e.range.getValues()[0].concat(name);

Storing values in array and retrieving from array when checkbox is checked

I am storing some values in array like this.
var test = [];
I am pushing the values to this array as test.push(sample);
I have some logic for calculating this value
var sample= (a/b.length)*100;
When I click on a button, the above logic for calculating value of sample is done and once I got the value of sample I am pushing it to test[] array. Now I want to retrieve all the values from the test[] array whenever I check the checkbox. I am able to do all this but I am facing a problem here. only the last pushed value is saving. but I want to save all the values that are being pushed. can anyone please help me in solving this issue.
Quick response is needed and appreciated
Regards
Hema
You need to use 2 dimensional array for this.
Use
var test= new Array();
then assign value test['someKey']=sample;
or test.push(sample); . you can retrieve array value like alert(test[0]) or by iterating array with $.each(test,function(index,value){alert(value)});
What you want to do is create an Array which would function as a list of value sets.
You would then be able to push all the changes into an array, and put it in the list.
for instance:
var mainList = new Array();
var changeListA = new Array();
var changeListB = new Array();
// do some stuff on change list **a** .. push(something)
changeListA .push(something);
changeListA .push(something);
changeListA .push(something);
// do some stuff on change list **b** .. push(something)
changeListB .push(changeListB);
mainList.push(changeListA);
Your question is not perfectly clear to me, however I can at least provide a small jsFiddle that proves to you that (how) array.push works.
Other answers indicate that what you want is either a two dimensional array, or a "hashmap" or "associative array" where the array values are stored using a key name. The code here can be used in the fiddle to achieve either or...
http://jsfiddle.net/xN3uL/1/
// First if you need 2 dimensional arrays:
myArray.push( ["Orange", "Apple"] );
myArray.push( ["Mango", "Pineapple"] );
// Secondly, if you need hashmap or associative array:
var myObj = {};
myObj['key'] = 'value';
alert(myObject.key);

Reading an input from a textbox and storing it in an array in JavaScript

I have a <textarea> that allows text to be inputted in the form of a string. Then the users clicks on a button which displays what they have inputted back to them in a text area within a table.
I need to use an array to store what has been inputted by the user, and then display it back out into another <textarea> element within a table from the array, where the user input is stored from the input box.
Any pointers on how to fill up an array and stacks, from a user input would be great.
You can declare your array like this
var yourArray = new Array();
or
var yourArray = [];
To add items to array:
yourArray.push(yourString);
To get you can use indexing like (almost any other language)
yourArray[i]
You can even set as an object array like this:
yourArray.push({ text : 'blablabla'})
So, in your case, filling up the array could be something like this:
var inputText = document.getElementById('id_of_input').value;
yourArray.push(inputText);
// show it
for(var i=0; i<yourArray.length; i++) {
alert(yourArray[i]);
}

How to dynamically update drop-down list options with values in a server-generated array

I have a web form with two drop-down boxes, and I'm looking for a way to dynamically update the options of the second box based on selections from the first.
The first box represents a data type, and the second box is a list of databases associated with the selected type.
I have the basic code running smoothly here:
var TypeA_DbSuffixList = ['Test1', 'Test2', 'Test3'];
var TypeB_DbSuffixList = ['TestA', 'TestB', 'TestC'];
function fill_dbSuffixList(){
document.getElementById("dbSuffixList").options.length = 0;
var suffixMenu = document.getElementById("dbSuffixList");
var dataFormat = document.getElementById("dataFormatType");
var suffixList = dataFormat.value + "dbSuffixList";
if (suffixList == 'TypeA_dbSuffixList') {
for(index in TypeA_dbSuffixList) {
suffixMenu.options[suffixMenu.options.length] = new Option(TypeA_dbSuffixList[index], index);
}
}
if (suffixList == 'TypeB_dbSuffixList') {
for(index in TypeB_dbSuffixList) {
suffixMenu.options[suffixMenu.options.length] = new Option(TypeB_dbSuffixList[index], index);
}
}
}
That code (activated whenever a selection is made in the dataType box) clears the existing list of options and repopulates the list based on the selected value of the "dataFormatType" box.
The problem that I face is that the actual lists of database tables are not hard coded and are instead generated with the following calls to the server to avoid repetitive editing of the page every time a new database is added:
var TypeA_dbSuffixList = ${TypeA_dbSuffixList};
var TypeB_dbSuffixList = ${TypeB_dbSuffixList};
These calls return the following code:
var TypeA_dbSuffixList = [Test1, Test2, Test3];
var TypeB_dbSuffixList = [TestA, TestB, TestC];
With the above code, the initial function treats each entry in the type arrays as an undefined variable, and nothing is ever written to the drop-down list.
If I were to add
var Test1 = "Apple";
var Test2 = "Orange";
var Test3 = "Grape";
prior to the "for" loop for TypeA, then selecting TypeA from the dataType drop-down list returns "Apple", "Orange", and "Grape" as the available databases for TypeA.
Visually, I see what needs to be changed. The [Test1, Test2, Test3] returns need to be ['Test1', 'Test2', 'Test3']. I'm just unsure exactly how to go about changing it, and have exhausted every web search I can think of.
Is there a way to either change the format of the returned arrays, or use the existing format and pass variable names as drop-down selections instead of using variable values?
Any help is greatly appreciated. I will continue to search for an answer on my own as well and will post it here should I find one.
I think the cleanest solution would be to change the code on the server-side to generate a proper JavaScript array of Strings, with the values enclosed in single or double quotes.
If that's not possible for some reason, and you want a pure-JavaScript solution, then I suggest you wrap the entire JSP/ASP/PHP variable (not sure what framework you're using) in double quotes, strip the string of brackets and spaces using a regex, and then split it into a string array using the comma as a delimiter.
So in your JavaScript, this:
var TypeA_dbSuffixList = ${TypeA_dbSuffixList};
would become this:
var TypeA_dbSuffixList = "${TypeA_dbSuffixList}".replace(/[\[\]\s]/g,"").split(",");
I think the best way to convert data in a server side language into something to be used in JavaScript is to JSON encode your objects.
I'm not sure what language your using on the server, but in PHP you can do the following
var arr = <?php echo json_encode( array ('abc', 'def', 'ghi') ); ?> ;
And your output will be
var arr = ['abc', 'def', 'ghi'] ;
This will make sure that strings with embedded new lines, tabs, quotes are properly escaped.
JSP
You said you're using JSP but the code you have looks more like velocity or free marker inside JSP. In JSP you could use the following, provided you download Gson
var TypeA_dbSuffixList = <%= new Gson().toJson(TypeA_dbSuffixList) %>;

Categories