I'm newbie at JavaScript, and i'm having some issues using parse Json.
I have one array in PHP, and i'm passing the values from the PHP to JavaScript.
The problem is that i inserted the values inside a While loop, and When i get multiple values:
Value 1
Value 2
I receive this:
[{"id":"1","value":"1","month":"2"}, {"id":"1","value":"2","month":"2"}]
And to print the values i have to do that:
alert(obj[0].name);
alert(obj[1].name);
And i want to print the values together
How can i use a for loop in this situation? I just need a simple example to implement on my code, thanks.
I think you can get the length of the array using obj.length and then iterate over them and put all the values in a single variable. and then print/alert.
var len= obj.length;
var str="";
for(i=0;i<=len;i++)
{
str+=obj[i].name+' ';
}
something in the line, tied to your requirements.
Hope it helps.
Related
i have following problem:
i have an array with a lot of data retrieved from mssql and hand it over to a jsp, i will simplify it in a example:
("test","1","test2","2")
those are 4 fields. With split(",") i seperate the 4 fields, so that i can take each value and assign them to html-objects.
Now through a coincidence i found out, that if the Array is filled as follows:
("test","1","test,2","2")
where "test,2" is one text, the split command seperates the 4 values to 5 values. Is there any alternative or way so that the split command ignores the "," that are part of a string of a field?
Greetings,
Kevin
Update:
Sorry for the missunderstandings guys here i tried to simplify the code as far as i can:
<script>
var jsArray = [];
<%
// Getting ArrayList from a request Attribute with a lot of data rows
ArrayList arrayList = (ArrayList)request.getAttribute("DSList");
for(int i=0;i<arrayList.size();i++){
%>
// Pushing each row to javascript array
jsArray.push("<%= ((ArrayList)arrayList.get(i))%>");
<%
}%>
// thats the split command that gets one line of the whole dataset
Stringarray = jsArray[x].substr(1,jsArray[x].length-2).split(","); // where x is the current record
</script>
now i can simply call each filed with
Stringarray[n] //where n is the field number
thats how the code looks like, the problem now is that if in one of the Strings in any record line is a "," then the split command obviously would give back the wrong field count. I hope now it's more clear what i mean
You can use non-greedy regex to filter out value inside "" and then remove "" from the words using array#map.
var string = '("test","1","test,2","2")';
var array = string.match(/"(.*?)"/g).map(function(item){
return item.replace(/"/g,'');
});
console.log(array);
Essentially, you have a backend data source and a front-end consumer. It just so happens that they reside on the same page, since you're using JSP to generate the page and the data. So treat it like a synchronous API, just embedded into the page.
How would you transmit data between and API and JavaScript? JSON.
So, stringify your result array into a JSON string and embed that into the JSP page, then JSON.parse() that in JavaScript and iterate as you would any other array.
Since I don't see your JSP code, I can't propose a more specific solution that what's linked here for creating JSON in JSP: how to add a list of string into json object in jsp? and Creating a json object in jsp and using it with JQuery
I have below jsoncode
{"0":{"category":"screensets","position":"top","rotate":"180","3d_file":"3d_deg_180.obj","height":"10","width":"10","x":"299","y":"166","current_roate":"0","comp_color":""},"width":"640","height":"640","name":"Test Drawing","size":"40","screen":"Conference set"}
How to decode in array format using jquery?
Small Example May be you help full
var j ='[{"id":"1","name":"test1"},{"id":"2","name":"test2"},{"id":"3","name":"test3"},{"id":"4","name":"test4"},{"id":"5","name":"test5"}]';
var json = $.parseJSON(j);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
$('.Record').append(k+" : "+ v+'<br>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Record"></div>
Seems like you are trying to turn all the contents of an object into an array, if I'm understanding correctly. This could be problematic.
Arrays in Javascript can't have named indices, so you can't have something like ['width'=>640] as you could in PHP. If that is what your looking for then you need another object to follow the following format {width:640}, much like you have right now. In other words, you need an object. Look at this for more details.
My recommendation is to figure out, or at least tell us, the purpose this JSON will accomplish as it is not a simple data structure.
This is javascript array
var data =['athar','naveed','123','abx'];
Now I want to access this array in code behind array or list variable. Don't want to use Hidden field.
If you want to use in anyother javascript function,you can simply use data[0] to access first element i.e.,athar.
data.length will give you the count of values present in the array.
I am trying to create a fairly complex system for my website. I want to be able to write some pseudo like code and then parse it to make it do something in my back-end.
My data is inside two $.each loops as this is an Object of data with multiple levels to it.
For instance, I want to take a string like this:
"<!this!> == <!PropertyStreetNumber!>"
Then how I would like for the above code to executed is this:
FormData[parentKey][this] == FormData[parentKey]["PropertyStreetNumber"]
Thanks for any help!
Here's some of my code, the code where this would need to go in (see commented area)
http://jsbin.com/liquvetapibu/1/
Is there any restriction not to use regular expressions on JavaScript?
You could do something like this:
var myString = "<!this!> == <!PropertyStreetNumber!>";
var aux = /<!(.*?)!> == <!(.*?)!>/.exec(myString);
The value of aux will be an array with 3 elements:
The string that was tested.
The first element within <! !>
The second element within <! !>
Then it would depend on what the content on each one is: in your example this is an object, while you seem to use PropertyStreetNumber as a string (maybe a typo?). If you want to use it as an object, you will have to use eval() (e.g.: eval(aux[1])) while if you want to use it as a string, you can use it directly (e.g.: aux[2]).
Conceptually, the first thing you would need to do is determine the type of statement you are working with. In this case, a comparison statement. So you need a regex statement to filter this into a "statement type".
Once you do that, you can figure out what the arguments are. So you create a regex to pull out the arguments on each side of the operator.
Next, the strings that represent action code items need to be parsed. The this argument is actually an object, whereas "PropertyStreetNumber" is a string. You've got to be able to determine which is which. Then you can filter that into a function that has been created specifically to handle those statements types.
If at all possible, I would try to avoid the use of eval(). You can get into trouble with it.
you could try with
var beg = str.indexOf("== <!") + 5;
to find the index of the beggining and then slice counting the chars from beginning like
str.slice(beg, -2);
and from there build the rest.
couldnt that work?`
I'm working on a score system that shows per question block, I'm using PHP to retrieve the data from a table and the javascript below to calculate the score. The problem is I want several score labels underneath each question block. So clearly I need an array to make this work, but currently I'm using this line to write the data onto document.getElementById("score_label[0]").innerHTML=""+current_score.toFixed(1);
so this only applies to the first entry in the array. How do I make it loop through the entire array(score_label[]) and increase it's value so the code reads document.getElementById("score_label[0]").innerHTML=""+current_score.toFixed(1);
document.getElementById("score_label[1]").innerHTML=""+current_score.toFixed(1);
this is the element javascript is writing to
echo "your total score: <span id='score_label[0]' name='score_board['".$score_board."']'></span>";
if there is need for I can post the entire function but I think it's mostly my lack of knowledge on arrays that's the issue here
If I'm reading your question correctly (current_score is the same for all elements???):
for (var i = 0; i < score_label.length; ++i)
document.getElementById("score_label[" + i + "]").innerHTML=""+current_score.toFixed(1);
I should mention that the id attribute of the form score_label[N] may be confusing.
Try to use foreach function to loop through the whole score_label array.
need to loop through a PHP array in JavaScript