I am storing field value (Sales, ProductName) from json in an array named 'data[]' and 'name[]'.
Below is the code which works fine.
function onCompletedCallback(response, eventArgs) {
var chartlist = eval("(" + response.get_responseData() + ")");
var markup = " ";
//Display the raw JSON response
markup += response.get_responseData();
// alert(markup);
var jsonData=jQuery.parseJSON(markup);
// alert(jsonData);
//declaring arrays
var name = [];
var data = [];
$.each(jsonData.d.results, function (index, value) {
data.push(value.Sales);
name.push(value.ProductName);
});
}
Now what I want to pass field values from dropdown(ddlxField) in my UI, which holds all the fieldname of the list and pass it to json object while pushing data in 'name' array.
For now am choosing 'ProductName' form dropdown, i.e, xName=ProductName
var xName = document.getElementById("ddlxField").value;
$.each(jsonData.d.results, function (index, value) {
data.push(value.Sales);
name.push(value.xName); // xname value= ProductName
});
But after execution, xName is coming out to be undefined.
can anyone suggest what else can be done or where am going wrong?
Use value[xName] instead of value.xName.
The [] syntax need a string for key, just like xName.
Related
I'm trying to work with this javascript code which gets HTML elements by their name and iterate over the array of them and pushing each into a JSON object. When I run this and print on the console (console.log()) the values array gets populated correctly but the data pushed into JSON is a repetition of one element. What I mean is it looks like this; What am I doing wrong?
4: {key: "Cars1", value: "march"}
5: {key: "Cars1", value: "march"}
else if (this.name == "cars") {
var values = $("#carsID").val();
$.each(values, function (index, value) {
jsonData["key"] = "Cars";
jsonData["value"] = value;
postData.RowInfo.push(jsonData);
});
The problem was that jsonData is declared outside this code block and doesn't get created for each element in the values array.
The corrected code;
else if (this.name == "cars") {
var values = $("#carsID").val();
$.each(values, function (index, value) {
var jsonDataEach = {};
jsonDataEach["key"] = "Cars";
jsonDataEach["value"] = value;
postData.RowInfo.push(jsonDataEach);
});
Been struggling with counting through this array. I was able to do it previously but I don't think I quite understand how the parameters of a function are assigned its data.
I am bringing in an array with from JSON data over AJAX, then using a .each loop to go through the data and count it. But I can't seem to count it when using the index parameter. It is just giving me the actual objects and not counting how many objects there are.
I was hoping that someone could help me understand why I am getting the object and not the count of objects in the array. What I have now is just my final attempt at getting it to count, I know it's wrong.
I am trying to count how many "results" there are in the array (that came from the JSON file).
I have added snippets of my code and attached a link to the JSON file. I have also marked the problem area with a comment saying Problem Area
CODE -
$.getJSON('http://api.fixer.io/latest?base=ZAR', {
action: "query",
list: "search",
format: "json",
}
, function (data) {
var baseCurr = data.base;
var baseDate = data.date;
$('#curr-cont').append('<div class="base row1" id="row1"><div class="base flag" id="flag"><i class="famfamfam-flag-za"></i></div><div class="base country-name"><p class="c-name" id="count-name">' + baseCurr + '</p></div><div class="base currency"><p class="c-amount" id="curr">' + baseDate + '</p></div></div>');
//***Problem Area***
var rates = [data];
$.each(rates[0], function (i, obj) {
console.log(obj);
});
$.each(data.rates, function (i, item) {
var amount = [item];
var name = [i];
var maxLength = 4;
var string = amount.toString();
string = string.substr(0, maxLength);
// amount = amount.substr(0, maxLength);
$('#curr-cont').append('<div class="row1" id="row1"><div class="flag" id="flag"><i class="famfamfam-flag-' + name + '"></i></div><div class="country-name"><p class="c-name" id="count-name">' + name + '</p></div><div class="currency"><p class="c-amount" id="curr">' + string + '</p></div></div>');
// if(i > 0){
// $('#list1').append('<li>' + name + '</li>');
// }
// else{
// $('#list2').append('<li>' + name + '</li>');
// }
});
});
JSON Data File
edit:
since rates is an object and not an array, you can do: Object.keys(data.rates).length.
Object.keys(...) will give you an array with all the keys in the object.
original:
If you want to know the number of rates in that file: data.rates.length will give you the length of the rates Array that is returned in the data.
No need to count it
EDIT 2
Check the fiddle - http://jsfiddle.net/SN5zT/2/
Following is the fiddle for which I am not sure why I am getting undefined in dropdown.
My fiddle - http://jsfiddle.net/z6GDj/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = new Array();
$.each(allSportPosition, function (index, value) {
values[index] = value;
});
//alert(values.length);
values.sort();
$.each(values, function (atIndex, atValue) {
sportPositionOptions = sportPositionOptions + '<option value="' + atIndex + '">' + atValue + '</option>';
});
$(sportPositionOptions).appendTo("#player");
} catch (e) {
alert("Parsing error:" + e);
}
$.each is automatically sorting keys to 25,26,27,28 for res.
Please explain the reason of this and why I am getting undefined ?
Let me know If i need to explain it more, I will surely do it :)
EDIT
Please explain the reason why it is getting sorted automatically http://jsfiddle.net/SN5zT/
Try
values.push(value);
instead of
values[index] = value;
Fiddle Link
The following script is working, I also figured out where the "undefineds" came from.
http://jsfiddle.net/z6GDj/3/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try{
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = allSportPosition;
//$.each(allSportPosition, function(index, value) {
// values[index] = value;
//});
//alert(values.length);
$.each(values,function(atIndex, atValue){
sportPositionOptions = sportPositionOptions+'<option value="'+atIndex+'">'+atValue+'</option>';
});
$(sportPositionOptions).appendTo("#player");
}
catch(e){
alert("Parsing error:"+ e);
}
The array is sorted automatically, because the keys are set correctly.
see http://www.w3schools.com/js/js_obj_array.asp. "An array can hold
many values under a single name, and you can access the values by
referring to an index number."
Or: Change the index, and you´re changing the order. (index indicates the order).
The undefined values are created by javascript default, check the last answer in here (How to append something to an array?)
"Also note that you don't have to add in order and you can actually
skip values, as in
myArray[myArray.length + 1000] = someValue;
In which case the values in between will have a value of undefined."
Since you are passing an object to each(), jquery passes the key as the index parameter. In your object, the keys are ranged from 25 to 28. Setting the array using the values[25] on an empty array will expand the array to index 25, with the first 25 elements undefined. Using values.push(value) will append the value at the end of the array.
$.each is doing the following assignment that is why you are getting so many undefined
values[25] = "Forwards (Strickers)"
values[26] = "Midfielders"
values[27] = "Fullbacks (Defenders)"
values[28] = "Goalkeeper"
During $.each browsers will automatically sort the keys if the keys are integer, one way to avoid this is use non integer keys
What you need to do is define your options before you sort them , and then append them to your select:
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '',
parsedJson = JSON.parse(res),
allSportPosition = parsedJson.allSportPosition,
options = new Array();
$.each(allSportPosition, function (index, value) {
options[index] = $('<option></option>', {
value: index,
text: value
});
});
$.each(options, function (index) {
$('#player').append(options[index]);
});
} catch (e) {
alert("Parsing error:" + e);
}
jsfiddle: http://jsfiddle.net/z6GDj/11/
I have a two part question (Very new to JSON)
I need to build a json object out of attr 'data-id'. Can a JSON object be a single 'array' of numbers?
I have got the code for this but I am struggling to build the JSON object, as follows:
code:
var displayed = {};
$('table#livefeed tr').each(function (i) {
var peopleID = $(this).attr("data-id");
//console.log("id: " + peopleID);
if(peopleID!="undefined") displayed += peopleID;
});
console.log(displayed);
However this does not work properly, I just end up with string of objects added together.
A JSON object can be an array of numbers.
Try something like this:
var displayed = [];
$('table#livefeed tr').each(function (i) {
var peopleID = $(this).attr("data-id");
if(peopleID!="undefined")
displayed.push(peopleID);
});
console.log(displayed);
To turn it into JSON,
JSON.stringify(displayed);
First you build and object then you use JSON.stringify(object); to create the string. But you also have an error. If you are checking peopleID to be defined you need to use typeof as an undefined attribute won't be the string 'undefined':
var displayed = [];
$('table#livefeed tr').each(function (i) {
var peopleID = $(this).attr("data-id");
//console.log("id: " + peopleID);
if(typeof(peopleID)!="undefined") displayed.push(peopleID);
});
console.log(displayed);
var jsonDisplay = JSON.stringify(displayed);
console.log("JSON: " + jsonDisplay);
I am trying to use an array as a key value type scenario and it is working with the exception that every value starts with 'undefined'. I believe this is due to the initial assignment being a += operator however I am not sure how to resolve it.
This is the code stripped of a lot of string concats....
var phasehtml = {};
$.each(json, function (i, item) {
phasehtml[item.Phase] += 'item:'+item.ID;
});
Basically I am trying to append the string to the appropriate key....
You can change the code to only append the ID if there's already IDs:
var phasehtml = {};
$.each(json, function (i, item) {
// Use the existing value for the phase, or an empty string that we can append to
var existingValue = (phasehtml.hasOwnProperty(item.Phase) ? phasehtml[item.Phase] : "");
phasehtml[item.Phase] = existingValue + 'item:' + item.ID;
});
That's assuming that you want phasehtml to contain an appended lists of the form "item:1item:2" for each phase.
The array you have posted is empty.
var phasehtml = {};
It seems that is the cause the following statement
phasehtml[item.Phase]
is being evaluated to "undefined".
Hmmm,
got the problem.
In your code you are trying to add with that value which is previously not defined that's why this error is occur.
In your code you have not initialize the variable that you are adding.
So try this:
var phasehtml = {};
$.each(json, function (i, item) {
phasehtml[item.Phase] = "";
phasehtml[item.Phase] += 'item:'+item.ID;
});
In this first assign some value, here is blank and then use that index of array.