currently working with jquery object
the object contains data like
data[0]={CustUserID: 31, FirstName: "System12", LastName: "Administrator", CustUserName: "SysAdmin"}
this object contains n number of records,and we get the length using data.length
and also each object each record contains different type of keys and n number of keys with value
so now i am trying to get each key name and value name from each record and need to show on page.
on html view:
CustUserID=31
FirstName=System12
LastName=Administrator
CustUserName=SysAdmin
the code i wrote for this is
var data="";
for(var i=0;i<data.length;i++)
{
data= data+"</br>CustUserID="+data[i].CustUserID+
"</br>FirstName="+data[i].FirstName+
"</br>LastName="+data[i].LastName+
"</br>CustUserName="+data[i].CustUserName;
}
$("#DivData").html(data);
but i stucked when data keys are dynamically changing according to user requirment so at that i am facing problem to get data, so i need to get key names and data should be looped dynamically.
please help me...
thank you guys..
You can use jQuery .each()
var data_result = '';
//first loop will go trough all data array elements
$.each(data, function(key, data_element){
// second loop will go trough all object keys
$.each(data_element, function(key, value){
data_result += '<br/>' + key + '= ' + value);
});
});
$("#DivData").html(data_result );
You can do this without jQuery too
var data = {
CustUserID: 31,
FirstName: "System12",
LastName: "Administrator",
CustUserName: "SysAdmin"
};
var dataHtml = '';
for (var p in data) {
if (data.hasOwnProperty(p)) {
dataHtml += '<br/>' + p + "=" + data[p];
}
}
$("#DivData").html(dataHtml);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="DivData"></div>
var mydata = Array(), result;
mydata[0]={CustUserID: 31, FirstName: "System12", LastName: "Administrator", CustUserName: "SysAdmin"};
for (var key in mydata[0]){
var obj = mydata[0][key];
result += '<br/>'+key+'='+obj;
}
jQuery("#myid").html(result);
Related
Ok, i know it might be simple for some guys, but i am trying this for hours and have no success till now.
if i have data in this array
var tDataValues = {
id: "TenantID",
text: "FullName",
username: "Username",
cnic: 'CNIC'
}
i am sending this variable to the function
commonSelect2Templating(selector,url,tDataValues,minInputLength,placeholder);
Note: I'm using Jquery Select2 (Sharing if it can help my question to understand.)
Then in that function in results Section i am trying to assign values
results: function(data, page) {
var newData = [];
var length = data.length + 1;
for(var i = 0; i<=length; i++){
}
$.each(data, function (index,value) {
newData.push({
id: value[tDataValues.id], //id part present in data
text: value[tDataValues.text] //string to be displayed
});
});
return { results: newData };
}
This is the data coming from the Server:
[{"TenantID":"13","FullName":"Rameez Hassana","Username":"Rameez","CNIC":"16141-6321136-1"},{"TenantID":"14","FullName":"Syed Haider Hassan","Username":"pakistanihaider","CNIC":"17301-5856870-1"},{"TenantID":"15","FullName":"Demo Tenant No 1","Username":"tn1","CNIC":"15165-6156685-6"}]
Coming to the The Problem:
Right now all the magic is happening here.
$.each(data, function (index,value) {
newData.push({
id: value[tDataValues.id], //id part present in data
text: value[tDataValues.text] //string to be displayed
});
Its Telling the code which is id and which is text, and it is working perfectly fine.
Now the Problem here is function i am trying to make is Common Function for the select2,
and if i have more values from db, like now i am getting from database how to make a loop and set those values one by one to its proper context.
e-g
tDataValues holds the fieldName cnic and server is sending the fieldName CNIC
so how to make a loop that if cnic exist in both then it should simply assign,
i can do that manually
newData.push({
cnic: value[tDataValues.cnic]
});
But like this it can not be a common function.
i can not simply make a logic how to implement this. did tried for hours but no success so far :(
Try:
for(var key in tDataValues) {
newData.push({ key: value[tDataValues[key]]});
}
Update:
then create an object first and push it to the array:
for(var key in tDataValues) {
var obj = {};
obj[key] = value[tDataValues[key]];
newData.push(obj);
}
check this, hope it helps
var mainData =[{"TenantID":"13","FullName":"Rameez Hassana","Username":"Rameez","CNIC":"16141-6321136-1"},{"TenantID":"14","FullName":"Syed Haider Hassan","Username":"pakistanihaider","CNIC":"17301-5856870-1"},{"TenantID":"15","FullName":"Demo Tenant No 1","Username":"tn1","CNIC":"15165-6156685-6"}];
var newData =[];
for(var i =0;i<mainData.length;i++){
for(var key in mainData[i]) {
var tempObj ={};
tempObj[key] = mainData[i][key];
newData.push(tempObj);
}
}
OUTPUT IS : [{"TenantID":"13"},{"FullName":"Rameez Hassana"},{"Username":"Rameez"},{"CNIC":"16141-6321136-1"},{"TenantID":"14"},{"FullName":"Syed Haider Hassan"},{"Username":"pakistanihaider"},{"CNIC":"17301-5856870-1"},{"TenantID":"15"},{"FullName":"Demo Tenant No 1"},{"Username":"tn1"},{"CNIC":"15165-6156685-6"}]
I'm trying to store an array in StriptProperties converting it to a string and recovering this way:
var personDataArr = ["Adam", "male", "programmer"];
function myFunction() {
var personDataStr = JSON.stringify(personDataArr);
ScriptProperties.setProperty('personData', personDataStr);
var personData = ScriptProperties.getProperty('personData');
personData = JSON.parse("[" + personData + "]");
Logger.log("personData[0] = " + personData[0]);
}
But when I log Logger.log("personData[0] = " + personData[0]); I get personData[0] = Adam,male,programmerinstead of Adam. Why? How to get, instead, the first element of the array?
You need to remove square brackets ( [] ) from JSON.parse function:
personData = JSON.parse( personData );
This happens because you create multidimentional array ant it looks in final result as:
[["Adam", "male", "programmer"]]
This is why 0 index of that array return Array for you and not Adam value
I have this currencies.json file:
{
"USD": {
"ValueUSD": 325.33,
"ValueEUR": 344.55,
"PreviousValueUSD": 324.55,
"PreviousValueEUR": 354.55,
},
"EUR": {
"ValueUSD": 325.33,
"ValueEUR": 344.55,
"PreviousValueUSD": 324.55,
"PreviousValueEUR": 354.55,
}
}
I need to parse it into "#content" using jQuery. Can someone help me with a code to do this? I think jSONP is needed because the feed is from another server.
Example for output needed:
<div class="currency">USD, 325.33, 344.55, 324.55, 354.55</div>
<div class="currency">EUR, 325.33, 344.55, 324.55, 354.55</div>
// you will get from server
var obj = $.parseJSON(data); // data contains the string
for (var key in obj) {
$('<div class="currency" />')
.html(key + ', ' + $.map(obj[key], function(val) { return val; })
.join(', ')).appendTo('body');
}
HERE is the code.
$.parseJSON is used to parse the string into the object.
Then for each currency inside object use .map() to map the values.
Join the values into a string separated by ,, append into the div and a currency name.
Resulting div append to the body.
Update (see comments):
If you want to retrieve this data cross-domain use:
$.getJSON('www.domain.com/currencies.json?callback=?', function(data) {
for (var key in data) {
$('<div class="currency" />')
.html(key + ', ' + $.map(data[key], function(val) { return val; })
.join(', ')).appendTo('body');
}
});
Something like this should help (the data parsed from your JSON above is held in the data variable):
var $body = $("body"),
key,
$div,
txt,
innerKey;
for (key in data) {
if (data.hasOwnProperty(key)) {
$div= $("<div></div").addClass("currency");
txt = [key, ", "];
for (innerKey in data[key]) {
if (data[key].hasOwnProperty(innerKey)) {
txt.push(data[key][innerKey]);
txt.push(", ");
}
}
// Remove the trailing comma
txt.pop();
// Set the HTML content of the div and then add to the body
$div.html(txt.join("")).appendTo($body);
}
}
Here's a working example jsFiddle.
well you can access things like:
data.USD.ValueUSD will get you 325.33 so you can do something liek this. pass your data object that you get from your ajax call in ur success func to call this function:
function populateContent(data){
var $currencyDiv = $('<div class="currency"></div>'),
$currencyDiv2 = $currencyDiv.clone();
$currencyDiv.html("USD, "+data.USD.ValueUSD + ", " + data.USD.ValueEUR + ", " + data.USD.PreviousValueUSD + ", " + data.USD.PreviousValueEUR);
//do the same for currencydiv2
//append your new content divs wherever you want
$('body').append($currencyDiv);
}
A more puristic approach that could also help you understand how to iterate through objects (and is browser native and therefore not relying on jQuery)
for(var data in #YOUR_JSON_DATA# ){ // iterate through the JSON nodes
var tmp = data; // store the current node in temporary variable
for(var val in json[data]){ // iterate through the current nodes' children
tmp += ", " + json[data][val]; // this is how you access multidimensional objects. format your output as you like
}
alert(tmp); // see the output. here you could use jquery to write this into your page.
}
I have a servlet which talks with the database then returns a list of ordered (ORDER BY time) objects. At the servlet part, I have
//access DB, returns a list of User objects, ordered
ArrayList users = MySQLDatabaseManager.selectUsers();
//construct response
JSONObject jsonResponse = new JSONObject();
int key = 0;
for(User user:users){
log("Retrieve User " + user.toString());
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", user.getName());
jsonObj.put("time", user.getTime());
jsonResponse.put(key, jsonObj);
key++;
}
//write out
out.print(jsonResponse);
From the log I can see that the database returns User objects in the correct order.
At the front-end, I have
success: function(jsonObj){
var json = JSON.parse(jsonObj);
var id = 0;
$.each(json,function(i,item) {
var time = item.time;
var name = item.name;
id++;
$("table#usertable tr:last").after('<tr><td>' + id + '</td><td width="20%">' + time +
'</td><td>' + name +
'</td></tr>');
});
},
But the order is changed.
I only noticed this when the returned list has large size (over 130 users).
I have tried to debug using Firebug, the "response tab" in Firebug shows the order of the list is different with the log in the servlet.
Did i do anything wrong?
EDIT: Example
{"0":{"time":"2011-07-18 18:14:28","email":"xxx#gmail.com","origin":"origin-xxx","source":"xxx","target":"xxx","url":"xxx"},
"1":{"time":"2011-07-18 18:29:16","email":"xxx#gmail.com","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"},
"2":
,...,
"143":{"time":"2011-08-09 09:57:27","email":"xxx#gmail.com","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"}
,...,
"134":{"time":"2011-08-05 06:02:57","email":"xxx#gmail.com","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"}}
As JSON objects do not inherently have an order, you should use an array within your JSON object to ensure order. As an example (based on your code):
jsonObj =
{ items:
[ { name: "Stack", time: "..." },
{ name: "Overflow", time: "..." },
{ name: "Rocks", time: "..." },
... ] };
This structure will ensure that your objects are inserted in the proper sequence.
Based on the JSON you have above, you could place the objects into an array and then sort the array.
var myArray = [];
var resultArray;
for (var j in jsonObj) {
myArray.push(j);
}
myArray = $.sort(myArray, function(a, b) { return parseInt(a) > parseInt(b); });
for (var i = 0; i < myArray.length; i++) {
resultArray.push(jsonObj[myArray[i]]);
}
//resultArray is now the elements in your jsonObj, properly sorted;
But maybe that's more complicated than you are looking for..
As mentioned by ghayes , json objects are unordered.
There are multiple solutions to this problem.
You can use array and the sort it to get the ordered list.
You can use gson library to get the desired order of elements.
I would prefer the second option as it is easy to use.
As JSONObject is order less and internally uses Hashmap. One way to use it to download the all classes from org.json and use in your project directly by changing the internal HashMap implementation to LinkedHashMap in JSONObject.java file. below is the sorted json files
https://github.com/abinash1/Sorted-Json-Object
I've got some JSON data that is giving me a list of languages with info like lat/lng, etc. It also contains a group value that I'm using for icons--and I want to build a legend with it. The JSON looks something like this:
{"markers":[
{"language":"Hungarian","group":"a", "value":"yes"},
{"language":"English", "group":"a", "value":"yes"},
{"language":"Ewe", "group":"b", "value":"no"},
{"language":"French", "group":"c", "value":"NA"}
]}
And I want to "filter" it to end up like this:
{"markers":[
{"group":"a", "value":"yes"},
{"group":"b", "value":"no"},
{"group":"c", "value":"NA"}
]}
Right now I've got this, using jQuery to create my legend..but of course it's pulling in all values:
$.getJSON("http://127.0.0.1:8000/dbMap/map.json", function(json){
$.each(json.markers, function(i, language){
$('<p>').html('<img src="http://mysite/group' + language.group + '.png\" />' + language.value).appendTo('#legend-contents');
});
});
How can I only grab the unique name/value pairs in the entire JSON object, for a given pair?
I'd transform the array of markers to a key value pair and then loop that objects properties.
var markers = [{"language":"Hungarian","group":"a", "value":"yes"},
{"language":"English", "group":"a", "value":"yes"},
{"language":"Ewe", "group":"b", "value":"no"},
{"language":"French", "group":"c", "value":"NA"}];
var uniqueGroups = {};
$.each(markers, function() {
uniqueGroups[this.group] = this.value;
});
then
$.each(uniqueGroups, function(g) {
$('<p>').html('<img src="http://mysite/group' + g + '.png\" />' + this).appendTo('#legend-contents');
});
or
for(var g in uniqueGroups)
{
$('<p>').html('<img src="http://mysite/group' + g + '.png\" />' + uniqueGroups[g]).appendTo('#legend-contents');
}
This code sample overwrites the unique value with the last value in the loop. If you want to use the first value instead you will have to perform some conditional check to see if the key exists.
How about something more generic?
function getDistinct(o, attr)
{
var answer = {};
$.each(o, function(index, record) {
answer[index[attr]] = answer[index[attr]] || [];
answer[index[attr]].push(record);
});
return answer; //return an object that has an entry for each unique value of attr in o as key, values will be an array of all the records that had this particular attr.
}
Not only such a function would return all the distinct values you specify but it will also group them if you need to access them.
In your sample you would use:
$.each(getDistinct(markers, "group"), function(groupName, recordArray)
{ var firstRecord = recordArray[0];
$('<p>').html('<img src="http://mysite/group' + groupName+ '.png\" />' + firstRecord.value).appendTo('#legend-contents');
}
See this-
Best way to query back unique attribute values in a javascript array of objects?
You just need a variation that checks for 2 values rather than 1.
var markers = _.uniq( _.collect( markers , function( x ){
return JSON.stringify( x );
}));
reference