Splitting data in my text field - javascript

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();
}

Related

Create variables based on array

I have the following array and a loop fetching the keys (https://jsfiddle.net/ytm04L53/)
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
alert(feed.match(/\d+$/));
}
The array will always contain different number of keys, What I would like to do is either use these keys as variables and assign the value after the : semicolon as its value or just create a new set of variables and assign the values found on these keys to them.
How can I achieve this? so that I can then perform some sort of comparison
if (test_user > 5000) {dosomething}
update
Thanks for the answers, how can I also create a set of variables and assign the array values to them? For instance something like the following.
valCount(feeds.split(","));
function valCount(t) {
if(t[0].match(/test_user_.*/))
var testUser = t[0].match(/\d+$/);
}
Obviously there is the possibility that sometimes there will only be 1 key in the array and some times 2 or 3, so t[0] won't always be test_user_
I need to somehow pass the array to a function and perform some sort of matching, if array key starts with test_user_ then grab the value and assign it to a define variable.
Thanks guys for all your help!
You can't (reasonably) create variables with dynamic names at runtime. (It is technically possible.)
Instead, you can create object properties:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":"); // Splits the string on the :
obj[parts[0]] = parts[1]; // Creates the property
});
Now, obj["test_user_201508_20150826080829.txt"] has the value "12345".
Live Example:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":");
obj[parts[0]] = parts[1];
});
snippet.log(obj["test_user_201508_20150826080829.txt"]);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
You can do it like this, using the split function:
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
console.log(feed.split(/[:]/));
}
This outputs:
["test_user_201508_20150826080829.txt", "12345"]
["test_user_list20150826", "666"]
["test_list_Summary20150826.txt", "321"]
Use the split method
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
feedMap = {}
for (i = 0; i < feeds.length; i++) {
var temp = feeds[i].split(':');
feedMap[temp[0]] = temp[1];
}
Yields:
{
"test_user_201508_20150826080829.txt":"12345",
"test_user_list20150826":"666",
"test_list_Summary20150826.txt":"321"
}
And can be accessed like:
feedMap["test_user_201508_20150826080829.txt"]
Here is a codepen
it is not very good idea but if you really need to create variables on-the-run here's the code:
for (i = 0; i < feeds.length; i++)
{
var feed = feeds[i];
window[feed.substring(0, feed.indexOf(":"))] = feed.match(/\d+$/);
}
alert(test_user_201508_20150826080829)
Of course you cannot have any variable-name-string containing banned signs (like '.')
Regards,
Michał

How to convert variable to two dimensional array using java script

I have a variable which contains data like this
var values = "VItDTotal,123,234,234,2345,1234,123,435,10,TestCase,123,234,234,2345,1234,123,435,5"
and I want to convert this string of data to a two dimensional array like this
[VItDTotal,123,234,234,2345,1234,123,435,10] //1st row
[TestCase, 123,234,234,2345,1234,123,435,5] //2nd row
How can I convert a JS variable to a two dimensional array?
I want to append these values to a datatable, how can I achieve this by using jQuery?
I hope this might help...
var values = "VItDTotal,123,234,234,2345,1234,123,435,10,TestCase,123,234,234,2345,1234,123,435,5"
var splittedArray = values.split(',')
var resultArray = new Array();
var resultKey = -1;
for(var i=0; i<splittedArray.length; i++) {
if(isNaN(splittedArray[i])) {
resultKey++;
resultArray[resultKey] = new Array();
resultArray[resultKey].push(splittedArray[i])
} else {
resultArray[resultKey].push(splittedArray[i])
}
}
I work this way:
//get the index where ",TestCase" is
var index = values.indexOf(",TestCase");
//create two arrays to the values
var part_one = [], part_two = [];
//slice the value from 0 to index and push part one
part_one.push(values.slice(0,index));
//slice the value from index+1 to the end and push part two
part_two.push(values.slice(index+1, values.length));
Not my favourite, but, are you after something like this?
var values = ["VItDTotal",123,234,234,2345,1234,123,435,10,"TestCase",123,234,234,2345,1234,123,435,5];
var vals = [values.
join(",").
replace(/,([a-z]+)(?!.*[a-z]+)/gi, " devider $1").
split(/\s+devider\s+/gi)];
console.log(vals);

Javascript Getting value from exact field from associative array

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);
}

Dynamically create a two dimensional Javascript Array

Can someone show me the javascript I need to use to dynamically create a two dimensional Javascript Array like below?
desired array contents:
[["test1","test2","test3","test4","test5"],["test6","test7","test8","test9","test10"]]
current invalid output from alert(outterArray):
"test6","test7","test8","test9","test10","test6","test7","test8","test9","test10"
JavaScript code:
var outterArray = new Array();
var innerArray = new Array();
var outterCount=0;
$something.each(function () {
var innerCount = 0;//should reset the inner array and overwrite previous values?
$something.somethingElse.each(function () {
innerArray[innerCount] = $(this).text();
innerCount++;
}
outterArray[outterCount] = innerArray;
outterCount++;
}
alert(outterArray);
This is pretty cut and dry, just set up a nested loop:
var count = 1;
var twoDimensionalArray =[];
for (var i=0;i<2;i++)
{
var data = [];
for (var j=0;j<5;j++)
{
data.push("Test" + count);
count++;
}
twoDimensionalArray.push(data);
}
It sounds like you want to map the array of text for each $something element into an outer jagged array. If so then try the following
var outterArray = [];
$something.each(function () {
var innerArray = [];
$(this).somethingElse.each(function () {
innerArray.push($(this).text());
});
outterArray.push(innerArray);
});
alert(outterArray);
A more flexible approach is to use raw objects, they are used in a similar way than dictionaries. Dynamically expendables and with more options to define the index (as string).
Here you have an example:
var myArray = {};
myArray[12]="banana";
myArray["superman"]=123;
myArray[13]={}; //here another dimension is created
myArray[13][55]="This is the second dimension";
You don't need to keep track of array lengths yourself; the runtime maintains the ".length" property for you. On top of that, there's the .push() method to add an element to the end of an array.
// ...
innerArray.push($(this).text());
// ...
outerArray.push(innerArray);
To make a new array, just use []:
innerArray = []; // new array for this row
Also "outer" has only one "t" :-)
[SEE IT IN ACTION ON JSFIDDLE] If that $something variable is a jQuery search, you can use .map() function like this:
var outterArray = [];
var outterArray = $('.something').map(function() {
// find .somethingElse inside current element
return [$(this).find('.somethingElse').map(function() {
return $(this).text();
}).get()]; // return an array of texts ['text1', 'text2','text3']
}).get(); // use .get() to get values only, as .map() normally returns jQuery wrapped array
// notice that this alert text1,text2,text3,text4,text5,text6
alert(outterArray);​
// even when the array is two dimensional as you can do this:
alert(outterArray[0]);
alert(outterArray[1]);
HTML:
<div class="something">
<span class="somethingElse">test1</span>
<span class="somethingElse">test2</span>
<span class="somethingElse">test3</span>
</div>
<div class="something">
<span class="somethingElse">test4</span>
<span class="somethingElse">test5</span>
<span class="somethingElse">test6</span>
</div>
Here you can see it working in a jsFiddle with your expected result: http://jsfiddle.net/gPKKG/2/
I had a similar issue recently while working on a Google Spreadsheet and came up with an answer similar to BrianV's:
// 1st nest to handle number of columns I'm formatting, 2nd nest to build 2d array
for (var i = 1; i <= 2; i++) {
tmpRange = sheet.getRange(Row + 1, Col + i, numCells2Format); // pass/fail cells
var d2Arr = [];
for (var j = 0; j < numCells2Format; j++) {
// 1st column of cells I'm formatting
if ( 1 == i) {
d2Arr[j] = ["center"];
// 2nd column of cells I'm formatting
} else if ( 2 == i ) {
d2Arr[j] = ["left"];
}
}
tmpRange.setHorizontalAlignments( d2Arr );
}
So, basically, I had to make the assignment d2Arr[index]=["some string"] in order to build the multidimensional array I was looking for. Since the number of cells I wanted to format can change from sheet to sheet, I wanted it generalized. The case I was working out required a 15-dimension array. Assigning a 1-D array to elements in a 1-D array ended up making the 15-D array I needed.
you can use Array.apply
Array.apply(0, Array(ARRAY_SIZE)).map((row, rowIndex) => {
return Array.apply(0, Array(ARRAY_SIZE)).map((column, columnIndex) => {
return null;
});
});`

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