i am not sure if its a total n00b question but here goes.
i have a JSON array with values:
array[0].1 = "the value I want"
now I want to include all "the value I want" into this one variable like:
the value I want [1], the value I want [2]....
how do i do it?
infact if there is a way I can get the comma seperated values into a variable as it is please let me know.
EDIT: CLARIFICATION OF QUESTION
I want to create a variable in which i want to append all the data from the JSON array i have.
for example, if the JSON data reads:
data[0] = value,
data[1] = value,
data[2] = value,
...
i want all the "value" appended into a variable.
var mystring=array.join(", "); maybe?
var b = 'I,am,a,JavaScript,hacker'
var temp = new Array();
temp = b.split(',');
Now the string has been split into 5 strings that are placed in the array temp. The commas themselves are gone.
temp[0] = 'I';
temp[1] = 'am';
temp[2] = 'a';
temp[3] = 'JavaScript';
temp[4] = 'hacker.';
Taken from QuirksMode.
join is the "opposite" of split - use it to append the elements of an array together into a variable.
var j = temp.join(','); // sets j to 'I,am,a,JavaScript,hacker'
Related
I think Im misunderstanding something here - I normally work in PHP and think I'm missing something small. My final array tmp is empty and displays as ",,,,,,,,,,,,,,,,". It seems to me my tmp array might be emptied somewhere or the scope gets reset for some reason. I'm using this as coordinates from a table where you can select table rows and posting to a webservice but my array seem to be erroneous.
var length = $("#arrayCount").html();
var letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var col = getSelectedColumn(); //for example sake lets say "B" is the selected column
var row = getSelectedRow(); //selected rows will be from "11" - "16"
var columnIndexStart = letters.indexOf(col[0]);
var tmp = [];
for(var i = row[0]; i <= row[1]; i++) //rows[0] = 11 and rows[1] = 16
{
tmp[i] = [];
for(var j = columnIndexStart; j < letters.length; j++) //columns and starts at index 1 if we work with "B"
{
var val = $("#" + i + "_" + letters[j]).html(); //using the row and letters as the associated DOM elements ID. Easier to retrieve it's HTML then.
if(val != undefined)
{
console.log("Index [" + i + "]['" + letters[j] + "'] = " + val); //works perfectly and prints as it should.
tmp[i]['"'+letters[j]+'"'] = val; //using quotes to save letters? Is this preferred?
}
}
}
console.log('Final Array: ' + tmp); //empty??
console.log('Final Array: ' + tmp[14]['G']); //testing HTML output. But is undefined.
return tmp;
Any help will be greatly appreciated.
Edited:
Example of console output.
My final array tmp is empty and displays as ",,,,,,,,,,,,,,,,"
With non-numeric index you are setting the field of object and not the element for index.
If you will have two-dimensional numeric array with numeric indices like the following:
var tmp = [[1,2,3], [1,2,3]];
after console.log('tmp = ' + tmp); you will obviously get the output string like:
tmp = 1,2,3,1,2,3
Because when you are trying to convert array to string it converts it elements to string and represent them with a commas.
However when you are trying to set element with non-numeric index, you are setting the field of this object.
var tmp = [];
tmp['A'] = 123;
console.log("tmp = " + tmp); // tmp =
console.log(tmp.A); //123
So, console.log in your case works good - it is serializing all elements of two-dimensional array. But no one array of the second level does not have stored values, it has only fields, which are not included in the string representation of array.
You are getting a set of commas, because each sub-array of tmp array does not contains any element, so it's string representation is an empty string. Each sub-array contains the required data into it's fields.
When you are performing sum operation of string and object you are forcing object to convert to string representation. Instead of this it is recommended to use console.log(yourObj) - it will log the whole object without converting it to string.
//using quotes to save letters? Is this preferred?
No, "A" and A are different identifiers.
var s = new Object();
s['"A"'] = 123;
console.log(s['A']); //undefined
console.log(s['"A"']); //123
Additionally, if you will set fields with quotes - you can not get the field in normal style:
console.log(s."A"); //syntax error : expected identifier after '.'
You can also just do this (use comma, not plus):
console.log('Final Array: ', tmp); //empty??
console.log('Final Array: ', tmp[14]['G']);
I have seen several posts on how to convert a string to an array using .split(), but I am curious how I would have a list re-sort it's self everytime a new string is added.
For example, I have an input box where I enter names in the format of 'First Last'. On the button click event, the input div clears, a dynamic list is generated of the names entered, and it reformats them 'Last, First'.
Every time a new name is entered, the list should resort itself alphabetically.
I would have this output div split itself on a delimiter after each name, so that the list is an indexed array of strings, but I don't have a delimiter to split on.
Here is my code so far. I know there are several things I could do to improve this but I'm looking for a very simple answer to storing these values in an array instead of a list of strings just so that they can be sorted alphabetically.
Assume all data will be entered in the format 'First Last' including capitalization.
The comment in all caps involves the 'combine' variable that needs to become an array.
var namesArr = [];//create an empty array that will hold the names
var output = document.getElementById('output');//get the output element (text area).
var name = document.getElementById('name');//get the textbox
function init(){
var nameBtn = document.getElementById('addNameBtn');//get the name button element
var clrBtn = document.getElementById('clearBtn');//get the clear button element
nameBtn.onclick = enterName;//set up your events here
clrBtn.onclick = clearNames;//set up your events here
}
function enterName(){
if(document.getElementById('name').value !==""){
var arr = document.getElementById('name').value.split(" ");
var space = ", ";
var firstname = arr[1];
var lastname = arr[0];
var outputA = [];
var combine = outputA+firstname+space+lastname+"\n";
output.value += combine//I NEED THIS OUTPUT VALUE
//TO BE STORED IN AN ARRAY
//EVERY TIME A NEW STRING IS ENTERED
//SO THAT I CAN USE .sort() on the array.
}
else{
alert("Please enter a name in the format 'First Last'");
}
if(document.getElementById('name').value !==""){
document.getElementById('name').value = "";//clear names input
}
}
function clearNames(){
document.getElementById('name').value = "";//clear names input
document.getElementById('output').value = "";//clear output input
}
init();//this will run when after the DOM loads
Thank you so much for any help or feedback.
You can use the .push() function to append the new name to the array and then sort the strings. Using the array that you have defined var namesArr = [];
namesArr.push(newLastFirstName);
namesArr.sort();
Then you can do what you want with the sorted array. (In this case outputting the list to the textarea element.)
Example:
var namesArr = [
"Smith, John",
"Philip, Bill",
"Power, Max",
"Bar, Foo"
];
// Once the name has been converted ("First Last" -> "Last, First")
// Append the name to the names array
namesArr.push("McFly, Marty");
// (Re-)sort the array since the new element has been added
namesArr.sort();
for(var i = 0; i < namesArr.length; i++) {
console.log(namesArr[i]);
}
Outputs:
Bar, Foo
McFly, Marty
Philip, Bill
Power, Max
Smith, John
I have a 2 dimension array defined as
var thischart = [[],[]];
and the array contains the following data created programatically:
1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,10,0,11,0,12,0,13,24,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0
I cannot get the single value of the second field in the particular array cell. For example, if I use the following command to get the value:
alert("thischart[i,1]=" + thischart[0, 1]);
I get the following answer:
thischart[i,1]=2,0
I tried using the second dimension to access the data as
thischart[0][1]);
but it gives me an error message:
I just want to get the second single value in the array such as for array cell 13 I want the value 24 from above. Does anyone have an answer on how to access this array?
I populated the array as follows and then updated it thru program logic:
$hours = [];
for($i = 0; $i< 24; $i++){
$hours[$i] = [];
$hours[$i][0] = ($i + 1);
$hours[$i][1] = "0";
}
And the answer to this question is below:
for(var i in thischart){
var tc = thischart[i];
myvalue = tc[1]); // this is the value I want
}
Thanks to everyone who responded.
For all of them like this:
for(var i in thischart){
var tc = thischart[i];
for(var n in tc){
// n is internal index
// tc[n] is internal value
}
}
For a single value from the first internal Array, the second value:
thischart[0][1];
Why don't you use the console to see what's the return of
thischart[0];
Because it should contain an array. If it does, then
thischart[0][1];
is perfectly valid syntax. And if it doesn't, then
thischart[0,1]
means nothing whatsoever.
Do something like this:
var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]); // 1
do you mean something like this:...
http://jsfiddle.net/DSrcz/1/
var arr = [1,0,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0];
arr[33]=1000;
alert(arr[13]);
alert(arr[33]);
i am trying to pass non numeric index values through JSON but am not getting the data.
var ConditionArray = new Array();
ConditionArray[0] = "1";
ConditionArray[1] = "2";
ConditionArray[2] = "3";
ConditionArray['module'] = "Test";
ConditionArray['table'] = "tab_test";
var Data = JSON.stringify(ConditionArray);
When i alert the Data Variable it has the Values 1,2 and 3 but module and table are not included. How can this be added so that the whole string is passed.
EDIT : And what if i have some multidimensional elements also included like
ConditionArray[0] = new Array();
ConditionArray[0] = "11";
JSON structure only recognizes numeric properties of an Array. Anything else is ignored.
You need an Object structure if you want to mix them.
var ConditionArray = new Object();
This would be an better approach:
var values = {
array : ["1", "2", "3"],
module : "Test",
table : "tab_test"
};
var data = JSON.stringify(values);
Since javascript array accepts numeric index only. If you want non numeric index,use Object instead.
var ConditionArray = {};
ConditionArray[0] = "1";
ConditionArray[1] = "2";
ConditionArray[2] = "3";
ConditionArray['module'] = "Test";
ConditionArray['table'] = "tab_test";
var Data = JSON.stringify(ConditionArray);
Here is the working DEMO : http://jsfiddle.net/cUhha/
According to the algorithm for JSON.stringfy (step 4b), only the (numeric) indices of arrays are stringified.
This is because Array does not contain your elements.
When you do this:
ConditionArray['module'] = "Test";
You actually add a property to the ConditionArray, not elements. While JSON.stringify converts to string only elements of the ConditionArray. For example:
var arr = new Array;
arr['str'] = 'string';
console.log(arr.length) //outputs 0
You need to use an Object instead of Array
If you change the first line to
var ConditionArray = new Object();
you will achieve the desired outcome.
If for some reason you cannot convert your array into object, for instance you are working on a big framework or legacy code that you dont want to touch and your job is only to add som feature which requires JSON API use, you should consider using JSON.stringify(json,function(k,v){}) version of the API.
In the function you can now decide what to do with value of key is of a specific type.
this is the way how I solved this problem
Where tblItemsTypeform is array and arrange is de index of the array
:
let itemsData = [];
for(var i = 0; i <= this.tblItemsTypeform.length -1;i++){
let itemsForms = {
arrange: i,
values: this.tblItemsTypeform[i]
}
itemsData.push(itemsForms)
}
And finally use this in a variable to send to api:
var data = JSON.stringify(itemsData)
have tried various things
split[6].length
String.split[6].length
along these lines without success get this error message for the last one ...
ReferenceError: "string" is not defined.
Hi Thanks for all the replies, in the end I created an array based on the index of the original array and then queried the length of that. As you can see I am having trouble removing single and double quotes from the input strings. New to javascript and its making me a little crazy lol.
// Loop through all the input messages
for (var i = 0; i < input.length; i++) {
var next = output.append(input[i]);
// Get the body of the current input message
var body = input[i].text;
// Set the body
next.text = body ;
next.text.replace(/\'/g, "'");
next.text.replace(/\"/g, """);
//replace(/['"]/g,'');
// Set a property
var split = next.text.split(",");
var array1 = split[5];
var array2 = split[2];
next.setProperty("aaaLength", split.length);
next.setProperty("aaaSplitValue", split.length);
next.setProperty("aaaArray1Value", split.length);
next.setProperty("aaaArray2Value", split.length);
if (next.getProperty("BaseFilename")=="name"){
next.text.replace(/\'/g, "'");
next.text.replace(/\"/g, """);
//replace(/['"]/g,'');
if(split.length>10){
next.setProperty("FullFilename","nameError"+i);
next.setProperty("BaseFilename","nameError"+i);
next.setProperty("Suffix",".err");
}
if(array1.length>10){
next.setProperty("FullFilename","nameSnameSuffixError"+i);
next.setProperty("BaseFilename","nameSnameSuffixError"+i);
next.setProperty("Suffix",".err");
}
}
Length should work if the elements are strings. See the following in action at http://jsfiddle.net/46nJw/
var parts = "foo,bar,baz,foop".split(/,/);
alert( parts[3].length ); // should alert 4
var arr = ['one','two','three']
arr[1].length
returns 3
Are you sure it is returning a string?
You can force it to convert to a string like so:
String(split[6]).length;
I don't know what you need, so I give you all the options I can think of:
var commaSeparatedString = "one, two, three";
var str = commaSeparatedString.split(",");
alert (str.length) // outputs '3'
alert (str[2]); // outputs 'three'
alert (str[2].length); //outputs '5'