Javascript Getting value from exact field from associative array - javascript

I have an associative array - indexed by dates. Every element holds another array.
[03/16/2015: Array[3], 03/17/2015: Array[3], 03/18/2015: Array[3], 03/19/2015: Array[3]]
I created it with this code:
array[cellDate][i]=cellText;
How can I get the value for example from cell 03/16/2015 array[2] ??
var text=array['03/16/2015'][2];
With this line of code I got an error.
EDIT:
http://www.traineffective.com/schedule/
I store in that array title of blocks dropped in the schedule (title of block of 'empty' value if cell is empty)
What I want to achive is remeber the order of the blocks for particular weeks , and when user changes week with arrows it loads block based on date withdrowed from array.
Code where I create array :
function saveWeekToArray(array){
var cellDate;
var cellText;
var tmpText;
var i;
workoutsTD.each(function(){
cellDate=$(this).attr("data-day");
array[cellDate]=['','',''];
i=0;
$(this).children('.workout-cell').each(function(){
if (!$(this).hasClass('workout-cell-empty')){
cellText=$(this).find('span').text();
array[cellDate][i]=cellText;
} else {
array[cellDate][i]='empty';
}
i++
});
});
}
Code where I load data from array (One with the error )
function loadBlocksFromArray(array){
var cellDate;
var cellText;
var tmpText;
var i;
workoutsTD.each(function(){
cellDate=$(this).attr("data-day");
i=0;
$(this).children('.workout-cell').each(function(){
if ((array[cellDate][i])!='empty'){
cellText=array[cellDate][i];
$(this).append(createBlock(cellText));
$(this).removeClass('workout-cell-empty');
}
i++;
});
});
}
When you will click sumbit button in console log you will see the structure of array.
I got error while changing the week its :
enter code hereUncaught TypeError: Cannot read property '0' of undefined

In Javascript, there is no concept of an associative array. You either have arrays (which are indexed by numbers) or you have Objects (whose elements are indexed by strings).
What you instead want is an object containing all of your arrays. For example:
var data = {
'3/4/2015' : ['val1', 'val2', 'val3'],
'3/8/2015' : ['val1', 'val2', 'val3']
};
Then you can access your elements in the way that you want:
var ele = data['3/4/2015'][1];

https://jsfiddle.net/x9dnwgwc/
That is the effect what I wanted achive. Thanks for hint Harvtronix!
var jsonObj = { workout : {} }
var i;
var k;
var workoutArray = [];
for(i=1; i<=7; i++){
var newWorkout = i+ "/12/2015";
for (k=0; k<=2; k++){
var newValue = "workoutTitle" + k;
workoutArray[k]=newValue;
}
jsonObj.workout[newWorkout]=workoutArray;
}
console.log(jsonObj);
for(i=1; i<=7; i++){
var newWorkout = i+ "/12/2015";
var tmpArray= jsonObj.workout[newWorkout];
console.log(tmpArray);
}

Related

Javascript code saving data to 2d array throws undefined

I'm writing a script that takes values from a html table, indexes them in aray and then assign every value to a tag in a form.Codepen https://codepen.io/anon/pen/eVLKyB
My problem is that after taking all specified values from array I get
Code responsible for indexing values from table look like this:
function size_index(){
var table = document.getElementsByClassName("product_table_cus");
var index= [[],[]];
var i_index = 0;
var iter = 0; //index of first dim of array
var len = table[0].rows.length;
console.log("Len:"+len);
while(i_index<len) {
//iterate trough rows
console.log("second for, iter:"+ i_index);
var col_inner = table[0].rows[i_index].cells[0].innerHTML; //size param
var col_param = table[0].rows[i_index].cells[1].innerHTML;//size value
var col_size = col_inner.substr(col_inner.indexOf(' ')+1);
console.log("Rozmiar:"+ col_size+" Wartość:"+col_param);
// index[1][0].push("col_size");
// index[i_index][1].push(col_param);
if(col_inner.search("Rozmiar")!==-1)
{
console.log("Inner wtf:"+col_inner+"Ite:"+iter);
index[iter].push(col_inner,col_param);
console.log("Index+:"+index[iter]);
console.log("Ind:"+col_inner+"Val:"+col_param);
}
else if(col_inner.search("Rozmiar")==-1){
}
iter++;
// col_param=0;
// col_size=0;
//iterate through columns
//columns would be accessed using the "col" variable assigned in the for loop
//rows would be accessed using the "row" variable assigned in the for loop
i_index++;
}
return index;
}
You can see it in the console log:
This line of code
console.log("Inner wtf:"+col_inner+"Ite:"+iter);
Produces this output
Inner wtf:Rozmiar XXLIte:2
Your index variable has exactly two values in it.
So of course, if iter is a value greater than one, this line will cause an error:
index[iter].push(col_inner,col_param);
There are two elements in index, so index[2] will return undefined.
Your underlying problem is that [[][]] is not a two dimensional array. It is an array containing two arrays.
A safer way to do this is:
var index= [];
Then, to add an element:
index[iter] = index[iter] || [];
index[iter].push(...);

Get the value from associative array in javascript

I want to get the value from array. I am using javascript.
My array is
[{"username1" : "123456"},{"username2" : "121"}]
I want to get the value of username1. I want print 123456 using username1. How it possible? Please help me? My code is shown below.
var categories = [];
categories.push({"username1" : "123456"});
for (var i = 0; i < categories.length; i++) {
for (var categoryid in categories[i]) {
var category = categories[i][categoryid];
// log progress to the console
console.log(categoryid + " : " + category);
}
It shows print all values and object in array.
That is not an "associative array" - it is a single dimensional array of objects.
An associative array would look like
var myArr = {"username1" : "123456","username2" : "121"};
And you would et your value using
var result = myArr.username1;
//or
var result = myArr["username1"];
To access your value using the example you posted you would use
var result = myArr.filter(x => x.username1)[0].username1;

Looping through dynamic JSON data using javascript

I am trying to display JSON data but the key value is dynamic it varies from one POST request to another my data hierarchy is as shown in diagram:
This is the part of the code I am running,Can anyone suggest me how to display JSON data where key showed in redbox gonna change for every POST request
$.ajax({
type: "POST",
url: "/",
dataType:'json',
data : { 'perfid': valueOne, 'hostname': $("#host").val(), 'iteration': valueThree},
success: function(data) {
$('#img1').hide();
var k = data[$("#host").val()].iscsi_lif.result.sectoutput.sect.length;
for(var i = 0; i < k; i++) {
var obj = k[i];
console.log(obj);
var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect.obj.avg_latency);
console.log(iscsi);
}
While running above snippet I am getting following error message :
data[$(....).val(...)].iscsi_lif.result.sectoutput.sect is undefined
You can use a "for in" loop to iterate over the keys of an object without having to specify the key names.
for( var key in myObject){
myValue = myObject[key];
// key will be your dynamically created keyname
}
So your code could be similar to the following:
...
success: function(data) {
$('#img1').hide();
var obj = data[$("#host").val()].iscsi_lif.result.sectoutput.sect;
for(var key in obj) {
if(obj.hasOwnProperty(key)){
var iscsi = parseInt(obj[key].avg_latency);
console.log(iscsi);
}
}
}
Solution Suggestion:
for (var key in object) {
if (object.hasOwnProperty(key)) {
var element = object[key];
}
}
Yet, in your situation, maybe you'll have to do this multiple times, so I would try to extract a generic function to do this and "normalize" the processing result to an expected format that wouldn't change.
The function will only run when the expected keys exist and since the forin loop uses the object keys, every object is processed dynamically.
This should work:
var k = data[$("#host").val()].iscsi_lif.result.sectoutput.sect;
for (var i = 0; i < k.length; i++) {
var obj = k[i];
console.log(obj);
var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect[obj].avg_latency);
console.log(iscsi);
}
The variable should be put inside brackets.
Also, it seemed to me that k was simply defined as length of an array, I removed that and put it to the for loop.
Since you have obj defined as varible you should use [], so it will be [obj], e.g :
var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect[obj].avg_latency);
Hope this helps.

Splitting data in my text field

Hello i am quite new to javascipt so please explain things clearly. I am currently running a php page which includes:
<input type="text" id="data"/>
<script>
document.getElementById("data").value = localStorage.getItem('itemsArray');
</script>
this items array contains objects which is saved like this:
function save(){
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {};
var num = document.getElementById("num").value;
newItem[num] = {
"methv": document.getElementById("methv").value
,'q1': document.getElementById("q1").value,
'q2':document.ge27548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}]tElementById("q2").value,
'q3':document.getElementById("q3").value,
'q4':document.getElementById("q4").value,
'comm':document.getElementById("comm").value
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));}
the result of the page appears like this:
[{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}]
is there anyway i can split the data so I can manipulate it one at a time like a loop or something. For example:
1st time:
{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}
Next:
{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}
etc.
Thanks.
You should JSON.parse() it like the save() method does when filling the oldItems array, then you can cycle the resulting array.
Example code:
<input type="text" id="data"/>
<script>
var myArray = JSON.parse(localStorage.getItem('itemsArray')) || [];
for (var i = 0; i < myArray.length; i++) {
var element = myArray[i];
// Do something with element.
}
</script>
The data is already returned in an array, which you can loop through with a standard for loop. However, you'll want to parse it first so that you then have an object that you can access using standard object methods.
For example:
var allItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
for(var i = 0; i < allItems.length; i++) {
var item = allItems[i];
console.log('Current item: %o', item);
// do whatever you want to it, etc.
}
Hi It looks like your save script is getting data from textfields and adding them as objects within an array.
the array is stored in your local storage and you can get it like this:
var items = JSON.parse(localStorage.getItem('itemsArray')) || [];
As this is an array you should be able to loop through it with a simple for loop:
for(var i in items){
// this has the i object within the array
var item = items[i];
// if you dont know the names of the keys in the array
// you can loop through this again using another loop
for(var j in item){
// you can then change this key like so:
items[i][j] = item[j].toUpperCase(); // (this makes the value upper-case for example)
}
// if you do know the names then you can just change them directly
items[i].q1 = items[i].q1.toUpperCase();
}

attempting to convert String data into numerical data, the drop the data into an array of arrays (Json)

I have this:
(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)
I'm attempting to get the output to look like this:
"coords": [[65.94647177615738, 87.890625],[47.040182144806664, 90],[45.089035564831036, 122.34375]]
Any Idea?
The first result comes back to me as a string, so when i try to assign the first object to an array, the console shows me this:
array is: "(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)"
var str = "(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)";
str = str.slice(1,-1); // remove outermost parentheses
var arrCoord = str.split(')(');
for (var i=0; i<arrCoord.length; i++) {
var tarr = arrCoord[i].split(", ");
for (var j=0; j<tarr.length; j++) {
tarr[j] = parseFloat(tarr[j]);
}
arrCoord[i] = tarr;
}
// arrCoord is now populated with arrays of numbers
Decided to sort of play code golf. Assuming:
var sample = '(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)';
Then:
var coords = sample
.split(/\(([^)]+)\)/)
.filter(function(v){return v!=""})
.map(function(v){return v.split(/[^0-9\.]+/)})

Categories

Resources