How to iterate in Jquery over json string with multiple objects - javascript

I'm wondering how I can access each object in this json string via jquery.
The string returned looks like:
{"Appointments":["\/Date(1507238100000)\/"],"Sessions":[]}
I need access to both the Appointments object as well as the Sessions object, I can't seem to figure it out.
I tried to access the Appointments object by index like:
$.each(data, function (index, element) {
$.each(data, function (index, element) {
//alert(JSON.stringify(element, null, 4));
alert(element.Appointments[index]);
});
//value = new Date(parseInt(element.Appointments.substr(6)));
//var rowContent = "<tr><td>" + value + "</td></tr>";
//$('#appointmentsTable tbody').append(rowContent);
});
This does not work however, thoughts?

You don't have to access element by element.Appointments[index] when you are looping though an array by $.each.
For example
var data = {"Appointments":["\/Date(1507238100000)\/"],"Sessions":[]};
To loop though object in data.Appointments, you simply do this
$.each(data.Appointments, function(index, element){
console.log(element);
});
To loop though object in data.Sessions, you simply do this
$.each(data.Sessions, function(index, element){
console.log(element);
});
For more example about $.each, please refer to JQuery API Documentation here.

You don't actually need jquery for this at all.
You could use plain javascript. If your project uses ES6, you could write it as:
// extract appointments and sessions from data
let { Appointments, Sessions } = data
// iterate over appointments
Appointments.forEach((appointment, index) => { console.log(appointment) })
// iterate over sessions
Sessions.forEach((session, index) => { console.log(session) })
Basically you don't really need index inside your iteration callback - you can directly access the elements you are iterating over instead. The same would apply to your jquery function as well.
If you prefer to use jQuery, your code could be rewritten as:
$.each(data.Appointments, (index, elem) => alert(elem))

Related

When stringifying an object, JSON turns element nodes into Objects?

So I'm working on a little personal project and I came upon a problem.
I need each day object to hold various dom element objects. These object instances are stored in an array and then that array needs to be stored into localStorage to load later.
The problem is when I do JSON.stringify and then JSON.parse it converts the HTML nodes into objects. So when I try to append element it tells me that the first parameter is not a node.
function save() {
localStorage.days = JSON.stringify(global.days);
localStorage.numberOfDays = global.numberOfDays;
localStorage.totalCount = global.totalCount;
}
function load() {
var parsedDays = JSON.parse(localStorage.days);
parsedDays.forEach(function(day){
document.getElementById("mainPage").appendChild(day.textObject);
});
anyone know how I can put an array of objects which hold elements into localStorage while keeping their node type????
If you will try to stringify dom nodes then it will return "{}".So its not possible to store node as it is inside localstorage.
What you can do is store information regarding nodes inside localstorage and recreate your node from that information and add it in your dom.
You'd probably need to have a property eg 'type' that defines the element type
var elem
parsedDays.forEach(function(day){
elem = document.getElementById("mainPage").createElement(day.type);
elem.attributes = day.attributes;
elem.innerHTML = day.textObject;
});
Or something like that, not too sure without seeing your day object
Use JSON.stringify and JSON.parse
Example Code:
Element.prototype.toJSON = function (){
return {nodeType:this.nodeType, outerHTML:this.outerHTML};
};
function replacer(k,v){
if(v.nodeType===1 && v.outerHTML){
var ele = document.createElement('html');
ele.innerHTML = v.outerHTML;
return ele.removeChild(ele.firstChild);
}
return v;
}
//test
var jstr = JSON.stringify({ele:document.body});
var json = JSON.parse(jstr,replacer);
console.log(jstr);
console.log(json);

Iterate over BasicPrimitives OrgChart Items

I'm using basic primitives org chart to create a family tree. What I'd like to do is iterate over the items that have been rendered so I can save the json to the database. I've been looking over the site's reference and put this in my code:
alert(primitives.famdiagram.ItemConfig.length);
$.each(primitives.famdiagram.ItemConfig, function (key, value) {
alert(value.Id);
});
for (var i=0; i < primitives.famdiagram.ItemConfig.length; i++)
{
alert(primitives.famdiagram.ItemConfig[i].Id);
}
It gives me a length of 5, but when I try to iterate through the items with either jquery or javascript, nothing happens. How can I access the collection of items using basic primitives?
This appears to work and I'd just have to rebuild the json string:
var items = jQuery("#famdiagram").famDiagram("option", "items");
$.each(items, function (key, value) {
alert(value.id);
alert(value.title);
alert(value.parents);
});
OR just save the items array in the DB as is.

How to access multi level object data with jQuery

I have this code in js, on click this happens:
var self = $(this);
self.click(function(e){
e.preventDefault();
var nid = self.parents('.innerContainer').attr('nid');
var subjectTitleNID = settings.xxxxx.yyyy["nid-" + nid]
Via HTML I can find the NID value of InnerContainer, which is the main parent.
From the console, if I run Drupal.settings.xxxx.yyyyy (where xxxx and yyyy are my destinations), I get a list of objects which are children.
["nid-463"]
["nid-465"]
["nid-466"] etc ....
nid-466 is the value assigned to VAR NID.
But what I need to find now, is:
1. How many children there are in ["nid-466"]
2. What are their values
Usually I would run a simple for loop, but I don't know how to target those values.
For example, I would do this:
for (i=0; i < dont know what to put here .length; i++) {
> Drupal.settings.xxxx.yyyy[nid-466][nid-??] // this is incorrect
}
See image for more detailed structure.
Any ideas?
Thanks
George
Use $.each loor for this:
$.each(Drupal.settings.xxxx.yyyy[nid-466], function(index, value) {
// index is a key
// value is a object
// put your code here
// console.log(value.nid);
})

Javascript/jQuery Dynamic Array

I am trying to create a dynamic array using JS/jQuery. The HTML structure is:
<ul>
<li><img src="1"/></li>
<li><img src="2"/></li>
<li><img src="3"/></li>
</ul>
I am trying to create a new array of the image sources, so it ends up looking like:
var imagesArray = [1, 2, 3];
I thought I could use the jQuery .each() method...but I keep getting lost. If you can please provide an explanation I would really appreciate it.
thanks!
var imagesArray = $('img').map(function(){ return this.src; }).get();
Here's a demo: http://jsfiddle.net/pkeBZ/
jQuery's .map() method loops through all the elements, collects whatever is returned from your callback function, and creates a new array out of it.
However, the returned result behaves like an array, but is really an jQuery object (granted, it probably makes no difference in your use case).
If you want to convert a jQuery object into an array, you can use jQuery's .get() method.
You thought correct :) You can use the jQuery .each() method.. as below..
<script type="text/javascript">
$(document).ready(function(){
var imagesArray =new Array();
$("ul li img").each(function(){
imagesArray.push($(this).attr('src'));
});
console.log(imagesArray); // this returns ["1", "2", "3"]
});
</script>
Use this code snippet to loop an array in jquery
1) First we declare an arrray
var MapAreas = [];
2) Now we loop using foreach
$.each(MapAreas, function (index, value) {
alert(index + ':' + value);
}
3) To check if a value is already present in an array use this code snippet
if ($.inArray(value, MapAreas) >= 0) {}
4) To remove an item from the array use this function
RemoveItemFromArray(value, arr) {
return jQuery.grep(arr, function (elem, index) {
return elem !== value;
});
}

Updating a Drop down list with Jquery from JSON

I have a list that I need to fill using a JSON collection of object. Here is what my action is returning:
public ActionResult GetProductCategories()
{
var categories = _entities.ProductCategories.ToList();
var result = new List<SelectListItem>();
foreach (var category in categories)
{
result.Add(new SelectListItem {Text = category.CategoryName, Value = category.CategoryId.ToString()});
}
return Json(result, JsonRequestBehavior.AllowGet);
}
This is what I've come up with for my javascript, gathered from various sources:
function loadCategories() {
$.getJSON("/Admin/Product/GetProductCategories", null, function (data) {
var selectList = $("#subCategories");
$.each(data, function(index, optionData)
{
var option = new Option(optionData.Text, optionData.Value);
selectList.add(option, null);
});
});
}
But it doesn't appear to be working, and isn't giving any errors. Whats the best practice for this sort of thing?
I was wondering what are you trying to achieve in this next lines of codes,
var option = new Option(optionData.Text, optionData.Value);
selectList.add(option, null);
are you trying to create an option then add it on select? if so, do it like this, use .append()
selectList.append(option);
with that, I'm still assuming new Option(optionData.Text, optionData.Value); is creating a new option, in jQuery it would be like this var option = $('<option>').text(optionData.Text).val(optionData.Value);
added notes for .add(),
var selectList = $("#subCategories"); // creates jQuery object selectList.
selectList.add(option, null); // selectList is jQuery object,
// so when you call .add(), you're calling jQuery's `add()`.
a workaround is this,
selectList[0].add(option, null); // you can use [0] to convert it into DOM object.
difference between:
DOM select object's .add()
jQuery object's .add()
JQuery fails silently if it doesn't like the JSON data coming back from the server. Point your browser at /Admin/Product/GetProductCategories and look at the result. Make sure it doesn't have any html tags and make sure there are double quotes around the key names.

Categories

Resources