Accessing Nested arrays in Json using .$each - javascript

So I'm having a problem accessing my json when its in a nested array. I previously had json set up like this with just one array and my .$each function worked perfectly. However I'm having trouble modifying it for this.
Json:
{
"tcontent": [{
"Name": "Septicaemia",
"url":"<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/septicaemia.jpg);'>",
"Variations": [{
"condition":"Community-acquired",
"organisms":"Staph. aureus",
"antimicrobial":"Flucloxacillin ",
"alternative":"(non anaphylaxis): ",
"comments": "Perform full septic screen."
}, {
"Condition":"Community-acquired if intra- abdominal source suspected",
"Organisms":"Predominantly Gram negatives and anaerobes Enterococci may also feature",
"Antimicrobial":"Co-amoxiclav 1.2g iv tds",
"Comments":"Perform full septic screen"
}, {
"Condition":"Healthcare-associated",
"Organisms":"Varies",
"Antimicrobial":"Piperacillin",
"Alternative":"Seek advice from Consultant Microbiologist",
"Comments":"Always"
}]
}, {
"Name": "Infective Endocarditis (IE) (pending blood culture results)",
"url":"<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/endocarditis.jpg);'>"
}, {
"Name": "Central Nervous System Infections",
"url":"<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/cns.jpg);'>"
}, {
"Name": "Skin and Soft Tissue Infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/skin.jpg);'>"
}, {
"Name": "Diabetic patients with foot infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/foot.jpg);'>"
}, {
"Name": "Bone and Joint Infections",
"url": "<a>",
"image":"<<div class='grid' style='background-image:url(img/anatomy/bone.jpg);'>"
}, {
"Name": "Intravascular Line Infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/intravascular.jpg);'>"
}, {
"Name": "Urinary Tract Infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/urinary.jpg);'>"
}, {
"Name": "Respiratory Tract Infections",
"url": "<a>",
"image":"<div class='grid' style='background-image:url(img/anatomy/respiratory.jpg);'>"
}, {
"Name": "Gastrointestinal Infections",
"url": "<a>",
"image":"<div class='grid' style='backgroundimage:url(img/anatomy/gastrointestinal.jpg);'>"
}]
}
Here's my javascript to access it.
$(function (){
var imp = "Json/therapy.json"
$.getJSON(imp, function(data) {
var info = "<br>";
$.each(data.tcontent, function(i, item) {
if(item.Name=='Septicaemia'){
var search = item.Variations;
$.each(item.Variations, function(j, subitem) {
info += subitem.condition + subitem.organisms + subitem.antimicrobial + subitem.alternative + subitem.comments
});
$(info).appendTo(".menu");
//alert(item)
};
});
});
});
I've tried a many variations on the var search but nothing seems to be working. I researched a lot of similar problems to this and I've been stuck on this for too long. Any light that can be shed on the situation would be much appreciated!

2 reasons why it doesn't work.
First of all javascript is case sensitive, Your variations differ.
subitem.condition fails on :
"Condition":"Community-acquired if intra- abdominal source suspected",
"Organisms":"Predominantly Gram negatives and anaerobes Enterococci may also feature",
"Antimicrobial":"Co-amoxiclav 1.2g iv tds",
"Comments":"Perform full septic screen"
So change "Condition" to "condition", etc.etc.
second reason is the
Change $(info).appendTo(".menu"); to $(".menu").append(info);
Why?
$(".menu").append(info) Will just paste the string in the selected DOM element.
But you use
$(info)... and jquery does all kinds of fancy stuff now.
It tries to either use it as DOM selector, or create a new element.
Because your info starts with <br> $(info) tries to create a DOM element and it removes all text. Leaving just <br> because br cannot contain content.
Try to remove the initial <br> then you will see following error:
Uncaught Error: Syntax error, unrecognized expression:Community-acquiredStaph. aureusFlucloxacillin...
For example if you would type $("hahaha") , Jquery will try to find the tag <hahaha>, So when you remove the <br> your $(info) is looking for the tag <Community-acquiredStaph. aureusFlucloxacillin...>.
But because your string would then contain weird characters like "-()." It will fail. Hence the above error.
So you can only add html like this:
$("<span>hahah</span>").appendTo($(".menu"));
Or use selector
$("#myDiv").appendTo($(".menu"));
An example when $(info).appendTo(".menu"); working is:
$.each(data.tcontent, function(i, item) {
if(item.Name=='Septicaemia'){
var search = item.Variations;
$.each(item.Variations, function(j, subitem) {
var info = "<p>" + subitem.condition + subitem.organisms + subitem.antimicrobial + subitem.alternative + subitem.comments + "</p>";
$(info).appendTo(".menu");
});
}
});
Using the following json:
http://pastebin.com/Bzpix1ai

Related

How to implement hyperlinks in JSON & D3 plugin?

My goal here is to have the childless nodes contain hyperlinks. This is the D3 plugin I'm basing things off of: https://github.com/deltoss/d3-mitch-tree
Image Example
I'm newer to JS and JSON so I'm having difficulties on figuring out how to proceed, especially since there's little to refer to in regard to hyperlinks & JSON. If there's a better way to go about this, I'm certainly open to new ideas.
Thank you in advance
<script src="https://cdn.jsdelivr.net/gh/deltoss/d3-mitch-tree#1.0.2/dist/js/d3-mitch-tree.min.js"></script>
<script>
var data = {
"id": 1,
"name": "Animals",
"type": "Root",
"description": "A living that feeds on organic matter",
"children": [
{
"id": 6,
"name": "Herbivores",
"type": "Type",
"description": "Diet consists solely of plant matter",
"children": [
{
"id": 7,
"name": "Angus Cattle",
"type": "Organism",
"description": "Scottish breed of black cattle",
"children": []
},
{
"id": 8,
"name": "Barb Horse",
"type": "Organism",
"description": "A breed of Northern African horses with high stamina and hardiness. Their generally hot temperament makes it harder to tame.",
"children": []
}
]
}
]
};
var treePlugin = new d3.mitchTree.boxedTree()
.setData(data)
.setElement(document.getElementById("visualisation"))
.setMinScale(0.5)
.setAllowZoom(false)
.setIdAccessor(function(data) {
return data.id;
})
.setChildrenAccessor(function(data) {
return data.children;
})
.setBodyDisplayTextAccessor(function(data) {
return data.description;
})
.setTitleDisplayTextAccessor(function(data) {
return data.name;
})
.initialize();
</script>
Chain this method before .initialize():
.on("nodeClick", function(event, index, arr) {
if (!event.data.children.length) {
console.log('you clicked a child-less item', event.data);
}
})
Inside the condition, event.data is the clicked childless item. Feel free to place URLs inside those objects and use those URLs to navigate away.
Taken from the repo's /examples folder, where I found one named Advanced example with Node Click Event.
According to the comment on the same page, you can also achieve this using the options syntax:
/* const tree = [
place your data here...
]; // */
new d3.mitchTree.boxedTree({
events: {
nodeClick({ data }) {
if (!data.children.length) {
console.log('You clicked a childless item', data);
}
}
}
})
.setData(tree)
// ...rest of chain
.initialize();

How to output JSON data, from an external API, in jQuery like I see it in the console log, in HTML (formatting JSON in jQuery)

Edit: I've had some luck with
var items = [];
$.each(response.response.content, function(i, item) {
$("#title").append(item.title + " ");
});
I've connected to an external API and can get everything printed out perfectly in my console log, but can only print it out in JSON format on my HTML page. I'm baffled as to why I can't figure out how to get it to print the same way on my page.
<script>
const settings = {
"async": true,
"crossDomain": true,
"url": "https://learning-objects-v2.p.rapidapi.com/search?keywords=Excel&lang=en&type=video&sort=popularity&model=strict&max=10&page=0",
"method": "GET",
"headers": {
"x-rapidapi-key": "12345678901234567890",
"x-rapidapi-host": "learning-objects-v2.p.rapidapi.com"
}
};
$.ajax(settings).done(function (response) {
$('#demo').append(JSON.stringify(response))
var items = [];
$.each(response.response.content, function(i, item) {
console.log(item);
});
});
</script>
And here is some of the JSON
"response":{
"content":[
{
"title":"Normal distribution excel exercise | Probability and Statistics | Khan
Academy",
"url":"https://www.youtube.com/watch?v=yTGEMoaWDCQ",
"description":"(Long-26 minutes) Presentation on spreadsheet to show that the normal distribution approximates the binomial distribution for a large number of trials. Watch the next lesson: https://www.khanacademy.org/math/probability/statistics-inferential/normal_distribution/v/ck12-org-normal-distribution-probl...",
"picture":"https://i.ytimg.com/vi/yTGEMoaWDCQ/hqdefault.jpg",
"provider":[
"YouTube"
],
"bloom":[
"discover"
],
"type":[
"Video"
],
"level":-0.5,
"learningTimeValue":26.07,
"learningTimeUnit":"min"
Here is an example of the console log
{title: "Excel Forecast Function Explained!", url: "https://www.youtube.com/watch?v=nRrZJpG_S7M", description: "This excel video tutorial provides a basic introdu…ted sales forecast in the future. My Website: ...", picture: "https://i.ytimg.com/vi/nRrZJpG_S7M/hqdefault.jpg", provider: Array(1), …}
bloom: ["discover"]
description: "This excel video tutorial provides a basic introduction into the forecast function which can be used to predict a y value given an x value. It could be used to predict the population at a certain year, the value of a car at a given time, or the estimated sales forecast in the future. My Website: ..."
learningTimeUnit: "min"
learningTimeValue: 10.3
level: -0.5
picture: "https://i.ytimg.com/vi/nRrZJpG_S7M/hqdefault.jpg"
provider: ["YouTube"]
title: "Excel Forecast Function Explained!"
type: ["Video"]
url: "https://www.youtube.com/watch?v=nRrZJpG_S7M"
I know I need to assign 's to it, and put it into a loop, but I'm not sure exactly how, and the books I have open aren't helping much. Thank you kindly!
You just need to use keyname to access required values i.e : title,pictures..etc .So , inside your each loop get that values and add them inside generated html and finally append this to your DOM.
Demo Code :
//just for demo ..suppose response variable have your response :
var response = {
"response": {
"content": [{
"title": "Normal distribution excel exercise | Probability and Statistics | Khan Academy ",
"url": "https://www.youtube.com/watch?v=yTGEMoaWDCQ",
"description": "(Long-26 minutes) Presentation on spreadsheet to show that the normal distribution approximates the binomial distribution for a large number of trials. Watch the next lesson: https://www.khanacademy.org/math/probability/statistics-inferential/normal_distribution/v/ck12-org-normal-distribution-probl...",
"picture": "https://i.ytimg.com/vi/yTGEMoaWDCQ/hqdefault.jpg",
"provider": [
"YouTube"
],
"bloom": [
"discover"
],
"type": [
"Video"
],
"level": -0.5,
"learningTimeValue": 26.07,
"learningTimeUnit": "min",
}, {
"title": "Normal distribution excel exercise | Probability and Statistics | Khan Academy2222 ",
"url": "https://www.youtube.com/watch?v=yTGEMoaWDCQ",
"description": "(Long-26 minutes) Presentation on spreadsheet to show that the normal distribution approximates the binomial distribution for a large number of trials. Watch the next lesson: https://www.khanacademy.org/math/probability/statistics-inferential/normal_distribution/v/ck12-org-normal-distribution-probl...",
"picture": "https://i.ytimg.com/vi/yTGEMoaWDCQ/hqdefault.jpg",
"provider": [
"YouTube"
],
"bloom": [
"discover"
],
"type": [
"Video"
],
"level": -0.5,
"learningTimeValue": 26.07,
"learningTimeUnit": "min",
}]
}
}
var html = ""
$.each(response.response.content, function(i, item) {
//just for demo ..
html += `<div><img src="${item.picture}"/>${item.title}</div>`
});
$("#somediv").html(html)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div id="somediv"></div>

How can I improve my search function Logic? Using Lunr.js

So I am using Lunr.js for my search function. Everything is working nice and dandy BUT, when I search certain keywords like "God" and "church" I get unacceptably long search times. I mean like, 30 secs and even beyond 1 min long. I'm sure it must be the logic I am using that is causing this, at least I think it is. The aim of my Search Function is to search the users input and return only the sentences where the key word is found along with the name of the book and the page where the searchQuery is found. My goal is to have a search function that can work offline. This is a Cordova project. I have commented everything so that you can follow the logic easily. Thank you for your time and input!
function searchFunction() {
//Clears results-wrapper Html element
document.querySelector(".results-wrapper").innerHTML = "";
//Store query in localDB
searchQuery = document.querySelector("#search-id").value;
localStorage.setItem("searchQuery", searchQuery);
//Returns from the index only the books which contains the query
var results = idx.search(searchQuery);
//Run through "results" and return all the text where the query is found
results.forEach(function (entry) {
//documents contains the database of all the books from my json file
documents.find(findSearchQuery);
//Searches only the text of the doc/books found in results variable
function findSearchQuery(doc) {
//searchQuery is the users input
let re = new RegExp(searchQuery, "i");
//if the book's name matches reference in "results"
if (doc.name == entry.ref) {
//And if the searchQuery is found in Books text
if (doc.text.match(re)) {
//Break up the block of text into sentences
var sentences = doc.text.match(/[^\.!\?]+[\.!\?]+/g);
sentences.forEach(function (sentence) {
//Find the sentence inside the sentences array and return the one with the searchQuery
//Populate HTML element "results-wrapper" with the results
if (sentence.match(re)) {
var anchor = document.createElement("a");
anchor.className = "anchorSearchResult";
anchor.href = doc.href;
//Create "div" element
var div = document.createElement("div");
div.className = "div-test";
//Creates "h4" element for title
var h4 = document.createElement("h4");
var title = document.createTextNode(doc.name);
h4.className = "title-results";
//Creates "p" element for sentence
var textElement = document.createElement(p);
var searchResult = document.createTextNode(sentence);
textElement.className = "text-results";
//Creates "p" element for page
var p = document.createElement("p");
var pageResult = document.createTextNode(doc.page);
p.className = "page-results";
h4.appendChild(title);
textElement.appendChild(searchResult);
p.appendChild(pageResult);
div.appendChild(h4);
div.appendChild(textElement);
div.appendChild(p);
anchor.appendChild(div);
document.querySelector(".results-wrapper").appendChild(anchor);
anchor.addEventListener("click", returnSearchResultId);
function returnSearchResultId(e) {
//store selectorId value of document
localStorage.setItem("selectorId", doc.selectorId);
}
// Highlight Function
var instance = new Mark(
document.querySelector(".results-wrapper")
);
instance.mark(searchQuery, {
element: "span",
className: "highlight",
});
}
});
}
}
}
});
}
And here is just a snippet of my json file that is loaded in my "documents" variable.
[
{
"name": "Pre-Eleventh-Hour Extra",
"year": "1941",
"text": "Pre-\"Eleventh Hour\" Extra MYSTERY OF MYSTERIES EXPOSED!",
"page": "1TR 2",
"href": "tracks/tr1.html#page-2.subHeading",
"selectorId": "#page-2\\.subHeading"
},
{
"name": "Pre-Eleventh-Hour Extra",
"year": "1941",
"text": "In the interest of reaching every truth-seeking mind that desires to escape the path that leads to destruction of both body and soul, this tract will be distributed free of charge as long as this issue lasts.",
"page": "1TR 2",
"href": "tracks/tr1.html#page-2.1",
"selectorId": "#page-2\\.1"
},
{
"name": "Pre-Eleventh-Hour Extra",
"year": "1941",
"text": "PREFACE PERSONALLY WATCHING FOR EVERY RAY OF LIGHT.",
"page": "1TR 3",
"href": "tracks/tr1.html#page-3.preface",
"selectorId": "#page-3\\.preface"
},
{
"name": "Pre-Eleventh-Hour Extra",
"year": "1941",
"text": "One who entrusts to another the investigation of a message from the Lord, is making flesh his arm, and thus is foolishly acting as without a mind of his own. And ”the mind that depends upon the judgment of others is certain, sooner or later, to be misled. ” -- Education, p. 231.",
"page": "1TR 3",
"href": "tracks/tr1.html#page-3.1",
"selectorId": "#page-3\\.1"
},
{
"name": "Pre-Eleventh-Hour Extra",
"year": "1941",
"text": "Similarly, one who allows prejudice to bar him from a candid investigation of anything new, coming in the name of the Lord, is unwittingly an infidel.",
"page": "1TR 3",
"href": "tracks/tr1.html#page-3.2",
"selectorId": "#page-3\\.2"
},
{
"name": "Pre-Eleventh-Hour Extra",
"year": "1941",
"text": "Likewise he who is satisfied with his present attainments in the Word of God, says in effect: \"I am rich, and increased with goods, and have need of nothing.",
"page": "1TR 3",
"href": "tracks/tr1.html#page-3.3",
"selectorId": "#page-3\\.3"
},
{
"name": "Pre-Eleventh-Hour Extra",
"year": "1941",
"text": "All these, in variously acting out the part which provoked the condemnation written against the Laodiceans, thereby fulfilling the prophecy which they ought not fulfill, are preparing themselves to be spued out (Rev. 3:14-18). And if they continue in their self-satisfied attitude that they have all the truth, and so have need of nothing more, they will spurn every new claimant to truth and toss the message into the discard because it comes through an unexpected channel. Certainly, then, were this tract not the unfolding of prophecy, the fact is inevitable that when the unfoldment did come, they would treat it in like manner, and consequently toss away their salvation!",
"page": "1TR 3",
"href": "tracks/tr1.html#page-3.4",
"selectorId": "#page-3\\.4"
},
{
"name": "Pre-Eleventh-Hour Extra",
"year": "1941",
"text": "Throughout the ages, all who have put their trust in the so-called wise men, and foremost Christians of the day, all reputedly godly men, have by these very ones been bereft of the crown of eternal life, as were the Jewish laity in the days of Christ because of their failing to assume full responsibility for their own salvation. Presumptuously trusting in the wisdom of their so-called \"great men,\" they declined to believe in Christ's words \"O Father, Lord of heaven and earth,...Thou hast hid these things from the wise and prudent, and hast revealed them unto babes.\" Matt. 11:25 \"Where is the wise? where is the scribe?...hath not God made foolish the wisdom of this world?\" 1 Cor 1:20.",
"page": "1TR 4",
"href": "tracks/tr1.html#page-4.1",
"selectorId": "#page-4\\.1"
}
]
Figured it out! It was the highlight functionality that I am getting from the Mark.js library that was causing the huge delay. After commenting it out, everything is lightening fast again.

Search functionality on nodes of D3 graph

So I've generated a JSON file with four tiers and I used D3.js's collapsing boxes format (https://bl.ocks.org/swayvil/b86f8d4941bdfcbfff8f69619cd2f460) to create a visualization.
The problem I am encountering is that because the JSON file is so large, the visualization won't even load into the HTML and even when it does, the boxes in the visualization lag and don't collapse as they should.
Therefore, I want to create a search form using Select2's dropdown box in HTML, so that users can enter a node/tier 1 value and the visualization will appear with only that specific sector shown. Since I am not good with Javascript I am finding quite hard to create such search functionality. I have assigned ID numbers to each value in the JSON but I'm not sure how to approach it further (and if this is even the correct direction to go in).
Below is a sample of my JSON code. So for example, if a user enters Lawyer and McDonald's, I want the visualization show only that node and it's children. I apologize if I'm unclear but any help would be great. Thanks so much!
{
"tree": {
"name": "Top Level",
"children": [
{
"name": "[('Lawyer', 'McDonald's')]",
"children": [
{
"name": "[('Doctor', 'Wendy's')]",
"percentage": "10%",
"duration": 5,
"children": [
{
"name": "[('Nurse', 'NYU')]",
"percentage": "1%",
"duration": 5,
"children": [
{
"name": "[('Pharmacist', 'LIU')]",
"percentage": "4%",
"duration": 5,
"id": "1.1.1.1"
},
{
"name": "[('PA', 'Wagner')]",
"percentage": "4%",
"duration": 5,
"id": "1.1.1.2"
}
],
"id": "1.1.1"
},
{
"name": "[('Surgeon', 'Harvard')]",
"percentage": "1%",
"duration": 3,
"children": [
{
"name": "[('Dentist', 'Buffalo')]",
"percentage": "1%",
"duration": 4,
"id": "1.1.2.1"
}
],
"id": "1.1.2"
}
],
"id": "1.1"
}
],
"id": "1"
},
{
There are a few things to change before you can actually make the D3 visualization work properly. Here are they.
(1) The data structure of the json doesn't match with the D3 code for displaying it. If you'd like to show the json data in the collapsing boxes properly adjust the below part of the code. d here corresponds with your children object and has properties; name, percentage, and duration
.append('xhtml').html(function(d) {
return '<div style="width: '
+ (rectNode.width - rectNode.textMargin * 2) + 'px; height: '
+ (rectNode.height - rectNode.textMargin * 2) + 'px;" class="node-text wordwrap">'
+ '<b>' + d.name + '</b><br><br>'
+ '<b>Percentage: </b>' + d.percentage + '<br>'
+ '<b>Duration: </b>' + d.duration + '<br>'
+ '</div>';
});
(2) Your data doesn't contain the following which is responsible for displaying the arrows properly when collapsing items into a parent box. This might be the case why the animation is not as it should.
"link" : {
"name" : "Link node 1 to 2.3",
"nodeName" : "NODE NAME 2.3",
"direction" : "ASYN"
},
(3) Here's the addition needed to implement the select2 drop-down box with all main branches.
HTML
<select class="js-example-basic-single" name="state">
JavaScript
$(document).ready(function() {
// map over all children in the main json branch
var dropdownData = json.tree.children.map(function(branch, i) {
return {
id: i,
text: branch.name,
}
});
// Add all branches to select2.
$('.js-example-basic-single').select2({
data: dropdownData
});
// Add change event listener. When an option is selected, clear the SVG and run treeBoxes function again.
$('.js-example-basic-single').change(function(e) {
$("#tree-container").empty();
var selectedBranch = e.target.value;
treeBoxes(null, json.tree.children[selectedBranch]);
});
});
Here's a live working example on JSFiddle that still needs some tweaking but it'll help you in the right direction.
NOTE: To make this example work, I've added the json in the html document instead of loading data from a file.

How to Get data in Json using javascripts?

Hi I'm currently creating an application to gather data form a website, and as I've researched you can used Json for that, now I have created a script to gather data, at first i have no problem with it, but when I cam across with a multi tree json i started having trouble.
here is my Json
{
"orders": [
{
"line_items": [
{
"id": 7660469767,
"name": "Personalised design - purple",
"properties": [
{
"name": "personalised text 1",
"value": "2"
},
{
"name": "personalised text 2",
"value": "Nuri &"
},
{
"name": "personalised text 3",
"value": "Samira"
}
],
}
]
}
]
}
I need to get the order.line_items.properties.value.
I tried this code but it says it does not work.
$.getJSON(order.json, function (data) {
$.each(data.orders.line_items.properties, function (index, value) {
$.each(this.value, function () {
console.log(this.text);
});
});
});
Can someone help me?
$.each(data.orders[0].line_items[0].properties, function (index, value) {
console.log(value.value);
});
Both orders and line_items are array, so it should have an access to array index first before accessing other object. And you don't have to use extra each in your code. The value above is an object for each properties. You can retrieve value there.

Categories

Resources