I have a json file with below mentioned format
mydata.json
{
"nodes":{
"Aidan":{"color":"green", "shape":"dot", "alpha":1, "id" : "aidan"},
"Sofia":{"color":"green", "shape":"dot", "alpha":1},
"Liam":{"color":"GoldenRod", "shape":"dot", "alpha":1}
},
"edges":{
"Quinn":{
"Liam":{"length":2.5,"weight":2},
"Audrey":{"length":2.5,"weight":2},
"Noah":{"length":2.5,"weight":2},
"Claire":{"length":2.5,"weight":2}
},
"Liam":{
"Sofia":{"length":2.5,"weight":2},
"Ethan":{"length":2.5,"weight":2},
"Amelia":{"length":2.5,"weight":2}
}
}
}
I will be reading above file data using jquery as mentioned below
var data = $.getJSON("data/mydata.json",function(data){
var nodes = data.nodes;
var edges = data.edges;
//i want to access first element or between element.
//like var edge = edges.get(0) or nodes.get("aidan")
})
I want to access first element or between element with the index or by name property of object. like var edge = edges.get(0) or nodes.get("aidan").
Thanks
There are several ways of doing it
Object.keys(nodes)[0]; //retrieve the first key
edges['Quinn'];
edges.Quinn
A little warning on the first one, Object in JS are unordered so it may break, thus browser tends to keep the insertion order.
hope it helped
Try this code
nodes['aidan']
edges['Quinn']
Either the before mentioned code
nodes['aidan']
or
nodes.aidan
should work equally fine.
Prepared a fiddle for you. You can check there.
Related
I am trying to write an html page for class that uses a drop down menu to allow users to pull up a list of relevant information. Unfortunately I am having trouble figuring out how to make the script call on the information in the array. The jsfiddle has the full html section, any help would be GREATLY appreciated.
Please bear in mind that I am not very good with terminology, so be as specific as possible. Especially regarding jQuery, our teacher didn't go over it much so it's a freaking mystery to me.
Also, I do plan on adding more information to the objects in the array, but until I get it working, I don't want to waste the time on something I might need to restructure.
http://jsfiddle.net/GamerGorman20/nw8Ln6ha/11/
var favWebComics = [
Goblins = {1: "www.goblinscomic.org"},
GirlGenious = {1: "www.girlgeniousonline.com"},
GrrlPower = {1: "www.grrlpowercomic.com"}
];
var myFunction = function() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
document.getElementById("web").innerHTML = favWebComics.x;
};
Again, the JSFiddle link has the full html, there are some unused items currently, but I do plan on adding more of them soon.
My next plan is to incorporate images into the objects, so a picture loads for each selection option. How would I manage that?
[ ] is used for arrays, which are indexed with numbers. If you want named properties, you should use an object, which uses { } for its literals:
var favWebComics = {
Goblins: "www.goblinscomic.org",
GirlGenious: "www.girlgeniousonline.com",
GrrlPower: "www.grrlpowercomic.com"
};
= is for assigning to variables, not specifying property names in an object.
Then you need to understand the difference between . and [] notation for accessing objects. .x means to look for a property literally named x, [x] means to use the value of x as the property name. See Dynamically access object property using variable.
So it should be:
document.getElementById("web").innerHTML = favWebComics[x];
your array is not structured correctly and an object would be better suited:
var favWebComics = {
Goblins : "www.goblinscomic.org",
GirlGenious : "www.girlgeniousonline.com",
GrrlPower : "www.grrlpowercomic.com"
};
then you should be able to access the properties as you intend
favWebComics.Goblins
favWebComics.GirlGenious
favWebComics.GrrlPower
Technically you were treating the array like a dictionary. if you're going to do that but still wanna add more information later you'll need to use brackets {} on the code.
var favWebComics = {
Goblins: ["www.goblinscomic.org"],
GirlGenious: ["www.girlgeniousonline.com"],
GrrlPower: ["www.grrlpowercomic.com"]
};
Also for javascript, as long as your searching key value stores, use braces [] for the call. Here's the working code below.
document.getElementById("web").innerHTML = favWebComics[x];
I have your solution, that displays:
the selected choice
the url
the images
Please check the fiddle.
http://jsfiddle.net/nw8Ln6ha/13/
Your object would be:
var favWebComics = {
Goblins : {url:"www.goblinscomic.org", img:"img1"},
GirlGenious : {url:"www.girlgeniousonline.com", img:"img2"},
GrrlPower : {url:"www.grrlpowercomic.com", img:"img3"}
};
Your display code:
document.getElementById("demo").innerHTML = "You selected: "+x+" "+ eval("favWebComics[\""+x+"\"].url")+" "+ eval("favWebComics[\""+x+"\"].img");
I have a link example this
Now I want to get the source of this page and extract the md5 hash value which is something like
<strong>MD5:</strong> 1b061e5530d2612135b8896482e68e3c</div>
<div>
I want to get the value 1b061e5530d2612135b8896482e68e3c from it.
I have made an GET request and got the source code in an variable like:
$.get(link).done(function(data){
alert(data);
});
This seems to be working fine but I have no Idea how to proceed further kindly help me .
I have Searched but not got any helpful result.
You could use good, old fashioned regexp (i.e., the second result of /MD5:<\/strong> (.*?)<\/div>/g).
var result = (/MD5:<\/strong> (.*?)<\/div>/g).exec([text])[1];
var regex = /MD5:<\/strong> (.*?)<\/div>/g;
var output=document.getElementById("output");
var test="<strong>MD5:</strong> 1b061e5530d2612135b8896482e68e3c</div>";
var matches = regex.exec(test);
output.innerHTML="MD5 is "+matches[1];
<div id="output"></div>
You can use xpath to get the text node containing the MD5 hash value:
$.get(link).done(function (data) {
var md5Node = document.evaluate('//*[#id="app_info"]/div[1]/div[2]/div[2]/div[1]/text()', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
var md5String = md5Node.textContent;
// ...
});
A better XPath
It would be better to find the MD5 text node based on its sibling's value. The XPath would look like
//*[text()="MD5:"]/../text()
Does the div you're trying to get the value from have an ID? If so you could try something like this
$.get(link).done(function(data){ console.log($(data).find("#idofdiv").text()); });
You could also use jQuery's .load function, like this:
$('div#container').load('external-page.html div#md5');
I'm saving user preferences using localStorage, like this:
choicesObject = { //put values in an object
"measure1" : $("#m1").is(':checked'),
"measure2" : $("#m2").is(':checked'),
"measure3" : $("#m3").is(':checked'),
"measure4" : $("#m4").is(':checked'),
"measure5" : $("#m5").is(':checked'),
"measure6" : $("#m6").is(':checked'),
"measure7" : $("#m7").is(':checked'),
"measure8" : $("#m8").is(':checked')
}
localStorage.setItem("choices", JSON.stringify(choicesObject));
Then I'm getting them back out like this:
retrieveChoices = localStorage.getItem("choices");
choicesObject = JSON.parse(retrieveChoices);
for(var i = 0;i<9 ;i++){
This nex t line is the problem:
ticked = choicesObject.measure+i;
It just doesn't work and I've tried using quotes and square brackets.
element = "#m" + i;
if(ticked==true){
$(element).prop('checked', true);
}
else{
$(element).prop('checked', false);
}
}
}
I want to loop though the measure properties and restore the checkbox elements.
I'm aware that even my object create is inefficient and I could use a for loop for that but I just don't know how to deal with object properties when it comes to looping because I don't get how you can do it without breaking the object.
At least that works and I can get data into and out of objects that get stored in localStorage, but this really simple issue has me stumped.
PS. Would
choicesObject = localStorage.getItem(JSON.parse("choices"));
be a better shorthand? Just thought this now whilst re-reading my question.
Edit: Thanks everyone. I got 3 correct answers so quickly! Amazing. Thanks so much. This site and its members amaze me every day and have revolutionised my coding!
I'm going to choose the correct answer as the one that also gave me the new shorthand for my parsing, but all of you gave me what i needed to know. I'm going to go see if I can answer some noob questions now!
Use
ticked = choicesObject["measure"+i];
EDIT: Your shorthand would not work, use instead:
choicesObject = JSON.parse(localStorage.getItem("choices"));
An object is just like a "dictionary" of values, so you can access a property either by doing myobject.propertyName or myobject["propertyname"]. They are equivalent.
In your case you just have to replace ticked = choicesObject.measure+i; with
ticked = choicesObject["measure"+i];
Also, consider using the var keyword when defining variables, each time you ommit it a new global variable will be created in the window object, that is the case for retrievedChoices and choicesObject. You can confirm this by accessing them via window["choicesObject"] or window.choicesObject or just choicesObject anywhere after that script has run.
A simple question I'm sure, but I can't figure it out.
I have some JSON returned from the server
while ($Row = mysql_fetch_array($params))
{
$jsondata[]= array('adc'=>$Row["adc"],
'adSNU'=>$Row["adSNU"],
'adname'=>$Row["adname"],
'adcl'=>$Row["adcl"],
'adt'=>$Row["adt"]);
};
echo json_encode(array("Ships" => $jsondata));
...which I use on the client side in an ajax call. It should be noted that the JSON is parsed into a globally declared object so to be available later, and that I've assumed that you know that I formated the ajax call properly...
if (ajaxRequest.readyState==4 && ajaxRequest.status==200 || ajaxRequest.status==0)
{
WShipsObject = JSON.parse(ajaxRequest.responseText);
var eeWShips = document.getElementById("eeWShipsContainer");
for (i=0;i<WShipsObject.Ships.length;i++)
{
newElement = WShipsObject.Ships;
newWShip = document.createElement("div");
newWShip.id = newElement[i].adSNU;
newWShip.class = newElement[i].adc;
eeWShips.appendChild(newWShip);
} // end for
}// If
You can see for example here that I've created HTML DIV elements inside a parent div with each new div having an id and a class. You will note also that I haven't used all the data returned in the object...
I use JQuery to handle the click on the object, and here is my problem, what I want to use is the id from the element to return another value, say for example adt value from the JSON at the same index. The trouble is that at the click event I no longer know the index because it is way after the element was created. ie I'm no longer in the forloop.
So how do I do this?
Here's what I tried, but I think I'm up the wrong tree... the .inArray() returns minus 1 in both test cases. Remember the object is globally available...
$(".wShip").click(function(){
var test1 = $.inArray(this.id, newElement.test);
var test2 = $.inArray(this.id, WShipsObject);
//alert(test1+"\n"+test2+"\n"+this.id);
});
For one you can simply use the ID attribute of the DIV to store a unique string, in your case it could be the index.
We do similar things in Google Closure / Javascript and if you wire up the event in the loop that you are creating the DIV in you can pass in a reference to the "current" object.
The later is the better / cleaner solution.
$(".wShip").click(function(){
var id = $(this).id;
var result;
WShipsObject.Ships.each(function(data) {
if(data.adSNU == id) {
result = data;
}
});
console.log(result);
}
I could not find a way of finding the index as asked, but I created a variation on the answer by Devraj.
In the solution I created a custom attribute called key into which I stored the index.
newWShip.key = i;
Later when I need the index back again I can use this.key inside the JQuery .click()method:
var key = this.key;
var adt = WShipsObject.Ships[key].adt;
You could argue that in fact I could store all the data into custom attributes, but I would argue that that would be unnecessary duplication of memory.
How can I get the id of the selected node in a jsTree?
function createNewNode() {
alert('test');
var tree = $.tree.reference("#basic_html");
selectedNodeId = xxxxxxxxx; //insert instruction to get id here
tree.create({ data : "New Node Name" }, selectedNodeId);
}
Unable to get harpo's solution to work, and unwilling to use Olivier's solution as it uses internal jsTree functions, I came up with a different approach.
$('#tree').jstree('get_selected').attr('id')
It's that simple. The get_selected function returns an array of selected list items. If you do .attr on that array, jQuery will look at the first item in the list. If you need IDs of multiple selections, then treat it as an array instead.
Nodes in jsTree are essentially wrapped list items. This will get you a reference to the first one.
var n = $.tree.focused().get_node('li:eq(0)')
You can replace $.tree.focused() if you have a reference to the tree.
To get the id, take the first matched element
if (n.length)
id = n[0].id
or you can use the jQuery attr function, which works on the first element in the set
id = n.attr('id');
In jstree version 3.1.1, you can get it directly from get_selected:
$("#<your tree container's id>").jstree("get_selected")
In the most recent version of jsTree (checked at 3.3.3), you can do this to get an array of IDs:
var ids = $('#tree').jstree('get_selected');
This will return, for example, ["selected_id1", "selected_id2", "selected_id3"]. If you want to get the selected nodes (not IDs), you can do this:
var nodes = $('#tree').jstree('get_selected', true);
The current docs contain more information.
$.jstree._reference('#my_tree_container')._get_node(null, true).each(function() {
id = $(this).attr("id");
alert('Id selected: ' + id);
});
I was having problems getting the selected ids from a tree with MULTIPLE selections. This is the way I got them:
var checked_ids = [];
$("#your-tree-id").jstree('get_selected').each(function(){
checked_ids.push($(this).data('id'));
});
In my case, the data call doesnt work.
I succeed in accessing my node data by using attr function.
$("#tree").jstree("get_selected").attr("my-data-name");
to get all selected ids use the below code
var selectedData = [];
var selectedIndexes;
selectedIndexes = $("#jstree").jstree("get_selected", true);
jQuery.each(selectedIndexes, function (index, value) {
selectedData.push(selectedIndexes[index].id);
});
now you have all the selected id's in the "selectedData" variable
<script type="text/javascript>
checked_ids.push($(this).context.id);
</script>
Just use
var nodeId = $('#FaqTreeView').jstree().get_selected("id")[0].id;
where #FaqTreeView is the id of your div that contains the jstree.
In some cases and/or jstree versions this solution doesn't work.
$('#tree').jstree('get_selected').attr('id');
Instead of defined "id" I get nothing.
What did the trick for me is:
$("#tree").jstree("get_selected").toString();
These are all old answers for old versions. As of version 3.3.3 this will work to get all attributes of the selected node.
$('#jstree').jstree().get_selected(true)[0]
If you then want the id then add .id at the end. You can look at all the other attributes in web developer tools if you copy the above code.
You can use the following code
var nodes = $("#jstree_demo_div").jstree(true).get_selected("full", true);//List of selected node
nodes[0].id//Which will give id of 1st object from array
With the latest version of jsTree, you can do it as follows:
var checked_ids = [];
$('#your-tree-id').jstree("get_checked",null,true).each(function(){
checked_ids.push(this.id);
});
alert(checked_ids.join(","));