MVC: Iterating a Viewbag array in javascript - javascript

The goal is to get the data from the ViewBag.Array to a Javascript array. The data is calculated in the controller so I cannot fetch it straight from the database. I need the data to draw a chart with jqplot. Code:
for(i = 0; i < #ViewBag.Array.Length; i++)
{
jScriptArray[i] = #ViewBag.Array[i];
}
The problem is "'i' does not exist in the current context" in the #ViewBag.Array[i] but has no problems in the jScriptArray[i]. Any help is appreciated.

You may try the following:
var array = #Html.Raw(Json.Encode(#ViewBag.Array));
for(var i = 0; i < array.length; i++) {
jScriptArray[i] = array[i];
}

var array=#Html.Raw(JsonConvert.SerializeObject(ViewBag.Array));
you can make use of JsonConvert.SerializeObject
Hope this Helps.

<script>
var jScriptArray=[];
#{
for(i = 0; i < ViewBag.Array.Length; i++){
<text>jScriptArray[#i] = "#ViewBag.Array[#i]";</text>
i++;
}
}
</script>
You will end up with something like this in html file:
jScriptArray[0] = "ArrayValue0";
jScriptArray[1] = "ArrayValue1";
jScriptArray[2] = "ArrayValue2";

The best way to achieve your goal is to create a JSON controller that returns the data into a JSON array.
From your javascript you can request the data and then process it.
Hope this helps

Related

Calculating with JSON array data

Stuck once again today, but i am trying to calculate with specific values from a JSON array. I can't seem to isolate the appropriate data. Can someone help me with this?
This is my JSON response:
[{"employee":[{"firstname":"Harry","birthdate":"1965-10-05","age":50}]},{"employee":[{"firstname":"Pete","birthdate":"1985-10-09","age":30}]}]
I'd like to get all the ages and add them for further use (for example average age). Help would be appreciated :)
Here is a working example for you:
var jsonData = [{"employee":[{"firstname":"Harry","birthdate":"1965-10-05","age":50}]},{"employee":[{"firstname":"Pete","birthdate":"1985-10-09","age":30}]}];
var sumOfAges = 0;
for(var i = 0; i<jsonData.length; i++){
sumOfAges += jsonData[i]["employee"][0].age;
}
console.log(sumOfAges);
var averageAge = sumOfAges / jsonData.length;
console.log(averageAge);
you can find the fiddle here:
http://jsfiddle.net/La9rzh8t/1/
Using Array#reduce and JSON#parse we can quite easily sum all ages of each employee in your data.
Here is a JSFiddle which uses the below function:
function sumAllAges(data) {
return data.reduce(function(total, obj) {
total += obj.employee[0].age;
return total;
}, 0);
}

Push multi-dimension array into another array

I have an multi-dimension array that i'm iterating through. Is there a way to put the contents of the array into a new multi-dimension array creating a new MDA? For example, the following code puts all indices of the original array into the new candies array if there's a match. Currently i'm doing
candies.push([product[0],product[1], etc...]);
I'm just trying to see if there's a faster/cleaner way to get that in there.
I tried:
candies.push(product);
but that didn't work. Here's the code i'm currently using
var sel = 'candy';
var candies = [];
for(var i = 1; i < products.length; i++) {
var product = products[i];
for(var j = 0; j < product.length; j++) {
if(sel==product[11]){
candies.push([product[0],product[1],product[2],product[3],product[4],product[5],product[6],product[7],product[8],product[9],product[10],product[11],product[12]]);
}
break;
}
}
A cleaner way of writing below line:
candies.push([product[0],product[1],product[2],product[3],product[4],product[5],product[6],product[7],product[8],product[9],product[10],product[11],product[12]]);
is:
candies.push(product.slice(0,13)]);
Sample example JSFiddle is here.
Best of luck.
(Mark this as answer if it serves your need.)

accessing nested properties based on structure

Could anyone please give me an alternate syntax to the following
var id = '-JLxSeCPUCVN13FxifTY';
var ResultsContainer = results[id];
var i=0;
for(var k in ResultsContainer)
{
var TheArrayOfObjectsThatIneed = ResultsContainer[Object.keys(ResultsContainer)[i]];
console.log(TheArrayOfObjectsThatIneed);
//loop the TheArrayOfObjectsThatIneed do the processing
i++;
}
as you see in the image i have an array within an object within an object and i have no idea what the property names are but the structure is always the same {results:{id:{idthatidontknow:[{}]}}} and all i need is to access the arrays
the above code is working nicely but i am new to javescript and i was wondering if there is a nicer syntax and if i am doing it the right way
Perhaps something like this?
var id = '-JLxSeCPUCVN13FxifTY';
var ResultsContainer = results[id];
for(var k in ResultsContainer) {
if (ResultsContainer.hasOwnProperty(k)) {
var TheArrayOfObjectsThatIneed = ResultsContainer[k];
console.log(TheArrayOfObjectsThatIneed);
//loop the TheArrayOfObjectsThatIneed do the processing
}
}

XML file in Javascript, getElementByAttribute

Let's suppose I have an XML file like this:
<?xml version="1.0" encoding="ISO-8859-1"?>
<MIDIFile>
<Event>
<Absolute>0</Absolute>
<NoteOn Channel="1" Note="40" Velocity="64"/>
</Event>
<Event>
<Absolute>236</Absolute>
<NoteOff Channel="1" Note="40" Velocity="0"/>
</Event>
</MIDIFile>
Thanks to some great tutorial I now know how to get these values in my javascript.
For example, I can iterate thru all the "Events" tag and get the "Absolute" value like this:
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","test.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
// make an array with all the events from the xml file
var events = xmlDoc.getElementsByTagName("Event")
for (var i = 0; i<events.length; i++)
console.log(events[i].getElementsByTagName("Absolute")[0].childNodes[0].nodeValue)
this will return
0
236
Now, how the hell can I access the "NoteOn" attribute and get its values? I want to iterate thru all the Events in the XML, see if they contains NoteOn or NoteOff and load an array with all the notes, their duration, velocity and channels.
Please help me! getElementsByTagName("NoteOn") just doesn't work... If it might help, here are some screenshot of what happens if I console.log(xmlDoc)
Thanks a lot in advance!
edit in response to an answer. As I try to do this:
var noteon = xmlDoc.getElementsByTagName('noteon');
console.log(noteon)
the result is just this one
[]
re-edit:
If I write "NoteOn" instead of "noteon" it works!
var noteon = xmlDoc.getElementsByTagName('noteon');
var note = new Array;
for(var i = 0; i < noteon.length; i++){
note[i] = noteon[i].getAttribute('Note'); // or any of the attributes you want to get
}
Edit:
If noteon = [] then you have 2 options you can put the whole thing in a try catch, not the best thing to do in javascript, or you can put it in an if statement. Something like this should work:
var noteon = xmlDoc.getElementsByTagName('noteon');
var noteoff = xmlDoc.getElementsByTagName('noteoff');
var note = new Array;
if(noteon != []){
for(var i = 0; i < noteon.length; i++){
note[i] = noteon[i].getAttribute('Note'); // or any of the attributes you want to get
} else if(noteoff != []){
for(var i = 0; i < noteoff.length; i++){
note[i] = noteoff[i].getAttribute('Note'); // or any of the attributes you want to get
} else{
return; //makes sure the function returns to the call even if nothing was found
}
}

Iterate through ViewData array and use javascript code

I have an array that is passed through the ViewData to my view. This array is composed of several elements of one of my Models.
I want to iterate through these elements and use javascript code with elements of the object.
Example in pseudo-code:
for x in ViewData["asdasd"] {
foo(x.Property)
}
foo is a javascript function.
How can i do this?
Use reflection to get the value. (edited because I realized I totally misunderstood the question at first)
#{
Type t = typeof(MyModelType);
foreach (string x in ViewData["mykey"])
{
var propertyVal = t.GetProperty(x).GetValue(MyModelObject, null);
#Html.Raw("foo('" + propertyVal + "')");
}
}
If I am correct try:
var myArray = new Array();
myArray = <%= ViewData[yourarray] %>;
for (var i = 0; i < myArray.length; i++) {
foo(myArray[i]);
//Do something
}
You could use something like this:
#{
foreach (var firstName in (ViewData["my_list"] as IEnumerable<string>)) {
#Html.Raw(firstName);<br />
}
}

Categories

Resources