I am preparing a chart in Javascript.
I have an array element named groupedByWeek
this groupedweek is derived from JSON data. Now i am having it in form of child arrays like this: groupedByWeek = Object { 1: Array[4], 2: Array[7], 3: Array[3] }
screenshot of console is here:
Now i want to parse each of groupedByWeek elements for graph, for the following code:
function increment(){
var i = groupedByWeek[1];
barChart1.parse(i,"json");
for (; i <= groupedByWeek.length; i++){
barChart1.parse(i,"json");
}
}
and
<input type="button" onClick="increment()" value="Next"/>
but this is not working!
Infact nothing is working out inside for loop while i am doing console.log()
If i am doing like this then it's working for 1st elemnt only!!:
var i = groupedByWeek[1];
barChart1.parse(i,"json");
please give me a hint how to work it out!
You have several problems:
Your array is containing an object, not an index.
You spelt length as legnth.
You should be attempting to iterate through your object, rather than an Array. So you would do something along these lines:
Javascript:
for(var index in object) {
// Do something.
}
jQuery:
$.each(object, function(index, value) {
// Do something.
});
I believe that was your original goal, iterate your object not a collection of the items.
Related
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.
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);
})
I have the following Json string. I want to get the 'Value' using 'Key', something like
giving 'BtchGotAdjust' returns 'Batch Got Adjusted';
var jsonstring=
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},]
Wow... Looks kind of tough! Seems like you need to manipulate it a bit. Instead of functions, we can create a new object this way:
var jsonstring =
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},];
var finalJSON = {};
for (var i in jsonstring)
finalJSON[jsonstring[i]["Key"]] = jsonstring[i]["Value"];
You can use it using:
finalJSON["BtchGotAdjust"]; // Batch Got Adjusted
As you have an array in your variable, you have to loop over the array and compare against the Key-Property of each element, something along the lines of this:
for (var i = 0; i < jsonstring.length; i++) {
if (jsonstring[i].Key === 'BtchGotAdjust') {
console.log(jsonstring[i].Value);
}
}
By the way, I think your variable name jsonstring is a little misleading. It does not contain a string. It contains an array. Still, the above code should give you a hint in the right direction.
Personally I would create a map from the array and then it acts like a dictionary giving you instantaneous access. You also only have to iterate through the array once to get all the data you need:
var objectArray = [{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"}]
var map = {}
for (var i=0; i < objectArray.length; i++){
map[objectArray[i].Key] = objectArray[i]
}
console.log(map);
alert(map["BtchGotAdjust"].Value)
alert(map["UnitToUnit"].Value)
See js fiddle here: http://jsfiddle.net/t2vrn1pq/1/
I am trying to get a file from user, convert it into an array and need to develop a histogram. For developing a histogram, I need to have that data in json format. Though there are enough example to convert an array into json hard coded, but I am not able to find a single example to convert it dynamically on real time basis. Here is my code:
<input type="file" name="F1" id="F1" size="80">
<input type="button" value="Read" name="B1" id="B1" onclick="execFile()">
function execFile() {
// main function to open, parse, and then render
var myfile=document.getElementById("F1")
arr = readCSV(myfile.value);
// parse csv line by line
for (var i=0;i<arr.length;i++) {
arr[i] = parseLineCSV(arr[i]);
}
for (var i=0;i<arr.length;i++) {
document.write(arr[i]);
}
}
So, I need to pass an array arr to convert to json. I found this code from another user but it seems not working for me.
for(var i=1;i<arr.length;i++) {
var tmp_values = [];
alert(arr.length);
for (var l=1;l<arr[0].length;l++) {
alert(arr[0].length);
tmp_values.push({label: arr[0][l], value: arr[i][l]}); //label + value respectively
alert("2");
}
jsonObj.push({key: arr[i][0], values: tmp_values}); //key
alert("3");
}
I am doing some mistake as I am able to get only arr.length and alert 3.. I am doing some mistake with push function, but cant figure out what. So , please help
I found this solution, normally this should do the trick.
var myJsonString = JSON.stringify(yourArray);
see here for more :
Convert array to JSON
Is it possible to delete an entry from a JavaScript array? The entry in the list gets replaced with null when delete operator is used.
data = [{pid:30, pname:abc}, {pid:31, pname:def}, {pid:32, pname:zxc}]
delete data[1]
becomes:
data = [{pid:30, pname:abc}, null, {pid:32, pname:zxc}]
FYI I'm getting this as json back from an ajax call. The returned value is parsed like var data = YAHOO.lang.JSON.parse(result.value || '[]')
What about sort()ing and then splice()ing the list?
There are many librarys out there that deal with the serialization and deserialzation of JSON content. Many of those librarys also allow you to manipulate the data from JSON also.
Depending on what language you're using will determine which library you decide to use.
More details would be helpful.
This is a problem with the JavaScript Array class. Deleting a value always leaves a hole. You need to create a new array without the hole. Something like this might be helpful:
Array.prototype.removeItem = function(index){
var newArray = []
for (var i =0; i < this.length; ++i){
if (i==index||typeof this[i] === "undefined") continue;
newArray.push(this[i]);
}
return newArray;
}
var a1 = [1,2,3,4,5]
delete a1[1]
alert(a1.join())
//prints 1,,3,4,5
var a2 = a1.removeItem(3)
alert(a2.join())
//prints 1,3,5 -- removed item 3 and previously "deleted" item 1