Issue passing MVC model array into javascript array - javascript

I'm trying to pass an array from my MVC Model into a javascript array (to use in fullCalendar), however having an issue.
From the below, "myArray" is being populated with the correct amount of items from the model array, but when I try to show obj.DateTime (valid field within the MVC model array) it returns undefined. The undefined alert appears the correct amount of times for items in the array.
Any help at all would be appreciated.
var myArray = [];
#foreach (var d in Model.Appointments)
{
#:myArray.push("#d");
}
myArray.forEach(function (obj) {
alert(obj.DateTime);
})

You can't use #d for converting your C# object to java-script object directly. You should encode your C# object to make a json value.
This code will encode (Serialize) your C# object to a JSON model.
#Html.Raw(Json.Encode(d));
Here is another question like yours

Related

How to iterate through an array send via AJAX in Java servlet?

I'm passing a json object in which value for the key is an array to a java servlet via AJAX.
{cruiseCodes: ["#1926","#7924","#1927"]}
And retrieving the value for cruiseCodes using req.getParameterValues("cruiseCodes"). How can I store these values into a java array or how can I iterate through the array values in java?
What I've currently done is created a json object and rewrote the data structure in java which outputs {cruise: ["#1926","#7924","#1927"]}
JSONObject obj = new JSONObject();
obj.put("cruise", req.getParameterValues("cruiseCodes"));
The following code worked eventhough the real concern was, is it really possible to copy an array just with the assignment operator. Any clarifications on that behalf is appreciated.
String [] array = req.getParameterValues("cruiseCodes");

How to do server-side rendering in Jade with an Array of json objects instead of a json object

On my Node.js sever, I have an array of JavaScript objects that were given to me by a MySQL query. I need to send that Array to my Jade template, so I do this in my router.js:
data = JSON.stringify(rows[0]);
res.render('yourUploads', {fromServer:data});
console.log(data) reads something like this: [{key:val},{key:val},{key:val}]
Now I'm trying to iterate over this object in Jade like so:
- for (object in JSON.parse(fromServer)) {
+posMixin(object.toString())
- }
object.toString() just gives me "0", "1", "2" object.val seems to be null.
I thought this was a duplicate of how to render json object in jade and loop through results, but I'm dealing with this Array of json instead of json. This is a lot like Passing an array to a JSON object for Jade rendering, but I'm trying to use a mixin and run sever-side rendering, not move it in to JavaScript.
For in loop work a bit different. It passes the key ( of your array), so you might need to loop over the array, and then over each key :
var arr=JSON.parse(fromServer);
arr.forEach(function(obj){
for(key in object){
console.log(key+":"+object[key]);
}
});

Javascript - key and value in array

I wish to store some data dynamically in an array, using Javascript. My goal is to save a configuration, that the user has specified, and later store it in my database.
I am trying to create a array like this:
var config = [];
config.push({id:100,name:'Yashwant',age:30});
config.push({id:200,name:'Mahesh',age:35});
However, when I print out the config array, like this:
alert(config);
it prints:
[object Object],[object Object]
How can I store and push values to my array, dynamically?
EDIT:: Seems like I am storing the values correctly. How can I access it?
Alert casts the config parameter to string. If you want to see the value for debugging purposes, it is better to use console.log(config).
Or you could use JSON.stringify(config) to convert it to JSON string.
To access the values, you can do this: console.log(config[0].age, config[1].age);
If you want to print values of any javascript object you can use JSON class to either stringify object data or parse stringified data (JSON) back to object.
alert(JSON.stringify(config));

How to convert JSON array property value from arrays to keys

I am a beginner programmer trying to convert JSON array property value from arrays to keys.
From
..,"searchResult":[{"itemId":["123"],"title":["abc"],..}]
to
..,"searchResult":[{"itemId":"123","title":"abc",..}]
Full original JSON result here with search result highlighted
the JSON array is being received in this code
//function to retrieve JSON arrays
function _cb_findItemsByKeywords(root) {
//Navigates and assigns variable "items" into the property, item
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var a = (items);
//assigned variable a to the array
}
Question: How do I remove the square brackets and check my array a?
EDIT:
Sorry for the confusion, My goal is to combine this array with [..] with another array without [..] before appending the properties to a table.
My plan:
If I understand your question correctly, you wish to convert a JSON array into a Javascript object, since altering JSON property values to keys wouldn't be valid JSON.
To convert JSON array into Javascript object, in pure Javascript you do:
JSON.parse(yourJSONgoeshere);
Docs and examples here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Hope it helps.

How do I attach JSON Stringify to a javascript variable

I have a variable :
var testData;
And I have a function that populates an array. Goes through an array and makes another array like so :
var person = {
"Name": obj.Name,
"Age": obj.Age,
}
partsObject.push(person);
I then want to make this array into JSON so I can use it with my D3 objects, so I do this :
testData = JSON.stringify(partsObject);
I can console log this variable, but when trying to go through it via D3's forEach method like so :
testData.forEach(function(d) // data is the JSON
{
I get the error Uncaught TypeError: testData.forEach is not a function
I don't understand how I can log the variable to the console yet it's as if I can't use it as JSON. Any ideas ?
As the name suggests stringify() converts a JavaScript object (the JSO in JSON) into a string of JSON. You can console.log() it because console.log expects to take a string, and anything that's not a string is converted to one to be displayed.
If you want to use it as an array again, you need to parse your string of JSON back to the JavaScript object: JSON.parse(testData).
You really dont need to stringify your Array to pass to d3. Do not to get confused with javascript objects, since forEach requires an array to loop through and you are passing a string to manipulate with forEach function
use:
partsObject.forEach(function(d)
{
...
JSON.stringify(partsObject); creates a string as"{'Name':'ABC','Age':23}"
Uncaught TypeError: testData.forEach is not a function caused because javascript was not able to find an Array
.stringify() turns a Javascript Object into a string. You would want to either run
partsObjects.forEach()
or alternativily you could turn the stringify'ed string back into an object with
(JSON.parse(testData)).forEach()
You are currently trying to loop through a String since you stringify your array.
Just do partsObject.forEach and don't stringify your Array.

Categories