I am developing a web application and I use jQuery 1.5 and JavaScript for the main functionality of the app. I connect from my app to a RESTful interface where I GET information for a person.
I use this function to retrieve the information from the json page:
var jqxhr = $.getJSON("example.json", function() { // store the data in a table }
My data in json format are like but I will get as a result more than one persons having the format of:
[{"person":{"time":"2010-02-18T17:59:44","id":1,"name": "John","age":60, "updated_at":"010-02-18T17:59:44"}}]
How can I store only the id, the name and the age of the person in a JavaScript table (to be more precise an array) and ignore the rest of the information?
Here is the specific JavaScript / jQuery you need, based on the MAP function.
var originalData = [
{ "person": { "time": "2010-02-18T17:59:34", "id": 1, "name": "John", "age": 60, "updated_at": "010-02-18T17:59:41"} },
{ "person": { "time": "2010-02-18T17:59:44", "id": 2, "name": "Bob", "age": 50, "updated_at": "010-02-18T17:59:42"} },
{ "person": { "time": "2010-02-18T17:59:54", "id": 3, "name": "Sam", "age": 40, "updated_at": "010-02-18T17:59:43"} }
];
var data = $.map(originalData, function (ele) {
return { id: ele.person.id, name: ele.person.name, age: ele.person.age };
});
Here is a full example that will convert and display the results in HTML.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="Styles/Site.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.6.1.js" type="text/javascript"></script>
<script type="text/javascript">
function CreateTableView(objArray, theme, enableHeader) {
// set optional theme parameter
if (theme === undefined) {
theme = 'mediumTable'; //default theme
}
if (enableHeader === undefined) {
enableHeader = true; //default enable headers
}
// If the returned data is an object do nothing, else try to parse
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '<table class="' + theme + '">';
// table head
if (enableHeader) {
str += '<thead><tr>';
for (var index in array[0]) {
str += '<th scope="col">' + index + '</th>';
}
str += '</tr></thead>';
}
// table body
str += '<tbody>';
for (var i = 0; i < array.length; i++) {
str += (i % 2 == 0) ? '<tr class="alt">' : '<tr>';
for (var index in array[i]) {
str += '<td>' + array[i][index] + '</td>';
}
str += '</tr>';
}
str += '</tbody>'
str += '</table>';
return str;
}
$(document).ready(function () {
var originalData = [
{ "person": { "time": "2010-02-18T17:59:34", "id": 1, "name": "John", "age": 60, "updated_at": "010-02-18T17:59:41"} },
{ "person": { "time": "2010-02-18T17:59:44", "id": 2, "name": "Bob", "age": 50, "updated_at": "010-02-18T17:59:42"} },
{ "person": { "time": "2010-02-18T17:59:54", "id": 3, "name": "Sam", "age": 40, "updated_at": "010-02-18T17:59:43"} }
];
var data = $.map(originalData, function (ele) {
return { id: ele.person.id, name: ele.person.name, age: ele.person.age };
});
$('#results').append(CreateTableView(data, 'lightPro', true));
});
</script>
</head>
<body>
<div id="results" style="width: 500px; margin: 20px auto;">
</div>
You can use jQuery's map function:
var data = $.map(originalData, function(person) {
return { id: person.id, name: person.name, age: person.age };
});
map basically converts each item in an Array, producing a new Array with the modified objects.
$.getJSON("example.json", function(data) {
var name = data.person.name;
var id = data.person.id;
var age = data.person.age;
}
what do exactly mean by a javascript table
u can store in a html table by
var $table = $("<table>
<tr><td>name</td><td>"+name+"</td></tr>
<tr><td>id</td><td>"+id+"</td></tr>
<tr><td>age</td><td>"+age+"</td></tr>
</table>");
Related
Hi (sorry for my english), I have this script:
<script type="text/javascript">
$(document).ready(function() {
var idPlato = decodeURI(getUrlVars()["idPl"]);
var url = "http://localhost/plato-datos.php?idPla="+idPlato+"";
});
};
</script>
It brings me this json from my database:
[{"category":"first","name":"green","idP":"1", "count":3},
{"category":"first","name":"blue","idP":"2","count":5},
{"category":"sec","name":"peter","idP":"3", "count":3},
{"category":"sec","name":"james","idP":"4", "count":2,},
{"category":"third","name":"dog","idP":"5", "count":4}]
I need to create one radiobuton for every name and group by categores
I create a solution. Kinda ugly but it will work:
var data = [{
"category": "first",
"name": "green",
"idP": "1",
"count": 3
}, {
"category": "first",
"name": "blue",
"idP": "2",
"count": 5
}, {
"category": "sec",
"name": "peter",
"idP": "3",
"count": 3
}, {
"category": "sec",
"name": "james",
"idP": "4",
"count": 2,
}, {
"category": "third",
"name": "dog",
"idP": "5",
"count": 4
}];
var result = {};
data.map(a => {
if (result[a.category]) {
result[a.category].push(a.name);
} else {
result[a.category] = [a.name];
}
});
Object.keys(result).map(category => {
var select = document.createElement('select');
result[category].map(name => {
var option = document.createElement('option');
option.value = name;
option.text = name;
select.appendChild(option);
});
document.body.appendChild(select);
});
Im working with jquery mobile then i used autodividersSelector function for group by the category JSON object, and build a radiobuton for every name
<script type="text/javascript">
//catch the JSON from my database
$(document).ready(function() {
var idPla = decodeURI(getUrlVars()["idPl"]);
var urlAder =
"http://localhost/lista-adereso.php?idPla=" + idPla + "";
//print the radiobutons
$.getJSON(urlAder, function(resultado) {
var allfiles = '';
for (var i = 0, aderesos = null; i <
resultado.length; i++) {
aderesos = resultado[i];
allfiles +='<li><label><input type="radio" data-
status="' + aderesos.aderesoCatNom +'"
name="name" id="id" value="' +
aderesos.aderNombre +'">'+
aderesos.aderNombre + '</label></li>'; }
//Group by categories
$('#linkList')
.empty()
.append(allfiles)
.listview({
autodividers:true,
autodividersSelector: function ( li ) {
var out = li.find('input').data("status");
return out;
}
})
.listview("refresh");
});
});
</script>
What I need:
append the data in array, then push in autocomplete js.
json:
{
"industry": [
{
"id": 16,
"name": "Agriculture & Forestry",
"industry_url": "agriculture-forestry"
},
{
"id": 3,
"name": "Apparel & Clothing",
"industry_url": "apparel-fashion"
},
{
"id": 56,
"name": "Architecture & Designing",
"industry_url": "architecture"
},
{
"id": 83,
"name": "Astrology",
"industry_url": "astrology"
}
]
}
code:
if (http.readyState == 4 && http.status == 200)
{
if (obj = JSON.parse(http.responseText), obj.industry.length > 0)
{
industry = document.getElementById("industry_url").getAttribute("value");
var industry = [];
for (var b = 0; b < obj.industry.length; b++)
{
//console.log(obj.industry[b]);
var indus=obj.industry[b];
var temp = new Object();
temp["name"] = indus.name;
temp["event_url"] = indus.industry_url;
industry.push(temp);
console.log(industry);
$('.autocomplete').autocomplete({
lookup: industry,
onSelect: function(suggestion) {
var thehtml = '<strong>industry name:</strong> ' + suggestion.name + ' <br> <strong>'+ suggestion.industry_url+'</strong>';
$('#outputcontent').html(thehtml);
}
});
html:
<input type="text" autocomplete="off" name="Industry" id="industry_name"
class="biginput autocomplete" placeholder="All Industry" id="ex3">
I have tried to google and find the jquery library.
Logic I found that is data would push in array first the push that array in autocomplete.
i have taken help from How do I pass this JSON data to an autocomplete
final code that i have dig but its also not working
$(document).ready(function(){
var arrayAutocomplete = new Array();
$.getJSON('apiurl', function(json)
{
console.log(json);
$.each(json.country,function(index, value){
console.log(value);
arrayAutocomplete = new Array();
arrayAutocomplete['text'] = value.text;
arrayAutocomplete['country_url'] = value.country_url;
});
$("#country_name").autocomplete({source: arrayAutocomplete});
});
});
Below is sample JSON response. I need to parse this in a generic way instead of using transactionList.transaction[0].
"rateType": interestonly,
"relationshipId": consumer,
"sourceCode": null,
"subType": null,
"transactionList": {
"transaction": [
{
"amount": {
"currencyCode": "USD",
"value": 1968.99
},
"customData": {
"valuePair": [
{
"name": "valuePair",
"value": "001"
}
]
},
"dateTimePosted": null,
"description": "xyz",
"id": "01",
"interestAmount": {
"currencyCode": "USD",
"value": 1250
},
"merchantCategoryCode": 987654321,
"principalAmount": {
"currencyCode": "USD",
"value": 1823.8
},
"source": "Mobile Deposit",
"status": "Posted",
"type": "1"
}
]
},
I am using the following code to parse json
$.each(jsonDataArr, recursive);
function recursive(key, val) {
if (val instanceof Object) {
list += "<tr><td colspan='2'>";
list += key + "</td></tr>";
$.each(val, recursive);
} else {
if(val != null) {
if(!val.hasOwnProperty(key)) {
list += "<tr><td>" + key + "</td><td>" + val + "</td></tr>";
}
}
}
}
and this outputs as transactionList
transaction
0 and then the other keys & values. I was hoping to get transactionList and all the keys and values instead of getting the transaction and the array element. So I guess my parsing logic is not correct. Can anyone help me address this so I can just have the transactionList displayed? Thanks for your help inadvance.
It would help if we had an example of your desired results.
What if there are multiple transactions in the transactionList, how would it be displayed?
Essentially your issue is that Arrays are Objects as well.
http://jsfiddle.net/v0gcroou/
if (transactionList.transaction instanceof Object) == true
Key of transactionList.transaction is 0
Instead you need to also test if the object is an array, and do something else based on the fact you're now parsing an array instead of a string or JSON object
(Object.prototype.toString.call(val) === '[object Array]')
Another easy way would be to check the 'number' === typeof key since your JSON object does not contain numeric keys, but array objects inherently do.
http://jsfiddle.net/h66tsm9u/
Looks like you want to display a table with all your data. I added border=1 to the tables to visualize the boxes. See an example in http://output.jsbin.com/wuwoga/7/embed?js,output
function display(data) {
var html = "<table border='1'>";
var lists = recursive(data);
html += lists + "</table>";
return html;
}
function recursive(json) {
var list = "";
var instanceObj = false;
$.each(json, function(key, val){
instanceObj = (val instanceof Object);
list += [
"<tr>",
"<td>" + key + "</td>",
(instanceObj) ?
"<td><table border='1'>" + recursive(val) + "</table></td>" :
"<td>" + val + "</td>",
"</tr>"
].join("");
});
return list;
}
If you call display(json) with the json below, you'd get a display of all your data. If you add more data in the transaction array, it will display that too
var json = {
"rateType": "interestonly",
"relationshipId": "consumer",
"sourceCode": null,
"subType": null,
"transactionList": {
"transaction": [
{
"amount": {
"currencyCode": "USD",
"value": 1968.99
},
"customData": {
"valuePair": [
{
"name": "valuePair",
"value": "001"
}
]
},
"dateTimePosted": null,
"description": "xyz",
"id": "01",
"interestAmount": {
"currencyCode": "USD",
"value": 1250
},
"merchantCategoryCode": 987654321,
"principalAmount": {
"currencyCode": "USD",
"value": 1823.8
},
"source": "Mobile Deposit",
"status": "Posted",
"type": "1"
}
]
}
};
I'm having some issues displaying multiple JSON arrays if anybody could help,
i would appreciate it.
JSON
{
"houseOne": [
{
"name": "John Clarke",
"age": 22,
"dob": "19-11-90"
},
{
"name": "Mitch Woodier",
"age": 20,
"dob": "23-10-92"
},
{
"name": "Mavis Waddingham",
"age": 21,
"dob": "10-11-91"
}
],
"houseTwo": [
{
"name": "Luke Woodier",
"age": 22,
"dob": "19-11-90"
},
{
"name": "Rob Clarke",
"age": 20,
"dob": "23-10-92"
},
{
"name": "Alex Gayfag",
"age": 21,
"dob": "10-11-91"
}
]
}
Javascript
<script type="text/javascript">
function ajaxRequest(url)
{
var request = new XMLHttpRequest();
// Work around for IE caching problem
if (url.indexOf('?') < 0) {
today = new Date();
url += '?' + today.getTime();
}
request.open("GET", url, false);
request.setRequestHeader("Cache-Control", "no-cache");
request.send();
return request.responseText;
}
var data = ajaxRequest("results.json");
var houses = JSON.parse(data);
function displayJson() {
var myDiv =document.getElementById("content");
for (house = 0; house < 3; house++) {
var home = houses.houseOne[house];
myDiv.innerHTML += houseDetails(home,house);
}
}
function houseDetails(home,houseNumber){
var myHTML = "<h1>House Mate "+ (houseNumber +1)+"</h1>";
myHTML += "<table>";
myHTML += "<tr><th>Name</th><th>Age</th><th>D.O.B</th></tr>";
myHTML += "<tr>";
myHTML += "<td>";
myHTML += home.name;
myHTML += "</td>";
myHTML += "<td>";
myHTML += home.age;
myHTML += "</td>";
myHTML += "<td>";
myHTML += home.dob;
myHTML += "</td>";
myHTML += "</table>";
return myHTML
}
</script>
Basically I can get it to display houseOne as a table but I can't get it to display both houseOne and houseTwo, I hope this is clear I'm not very good with web dev.
Regards,
Dean
In your displayJson() function you're only referencing house.houseOne
var home = houses.houseOne[house];
Here's an updated version (I've added jQuery too) http://jsfiddle.net/XzZUR/1/
JSON
var houses = {
"houseOne": [{
"name": "John Clarke",
"age": 22,
"dob": "19-11-90"
}, {
"name": "Mitch Woodier",
"age": 20,
"dob": "23-10-92"
}, {
"name": "Mavis Waddingham",
"age": 21,
"dob": "10-11-91"
}],
"houseTwo": [{
"name": "Luke Woodier",
"age": 22,
"dob": "19-11-90"
}, {
"name": "Rob Clarke",
"age": 20,
"dob": "23-10-92"
}, {
"name": "Alex Gayfag",
"age": 21,
"dob": "10-11-91"
}]
};
Javascript
function displayJson() {
var myDiv = $("#content");
$.each(houses, function(){
var house = this;
$(house).each(function(key){
myDiv.append(houseDetails(this,key));
})
});
}
I'd recommend not using synchronous ajax request, it would be better to use a callback.
You could itterate through every house object like so:
function displayJson() {
var i,h,ret=[];
var myDiv =document.getElementById("content");
// houseone and housetwo
for (h in houses) {
// houseone and housetwo are arrays: [house,house,house]
// for every house in this array do:
for(i=0;i<houses[h].length;i++){
var home = houses[h][i];
ret.push(houseDetails(home,i));
}
}
//setting innerHTML is resource intensive
// no reason to do this within a loop.
myDiv.innerHTML=ret.join("");
}
I have some JSON data (simple array of objects) .
var input= [
{
"cat": "some",
"id": "0"
},
{
"cat": "some",
"id": "1"
},
{
"cat": "some/category",
"id": "2"
},
{
"cat": "some/category/sub",
"id": "3"
},
{
"cat": "some/other",
"id": "4"
},
{
"cat": "some/thing/different",
"id": "5"
},
{
"cat": "some/thing/different",
"id": "6"
},
{
"cat": "yet/another",
"id": "7"
}
]
I wanted to generate nested html list out of it based on categories:
some
0
1
category
2
sub
3
other
4
thing
different
5
6
yet
another
7
My first step was to create empty nested object using the function:
createNestedObject = function(base, names) {
var = 0;
var results = [];
while (i < names.length) {
base = base[names[i]] = base[names[i]] || {};
results.push(i++);
}
return results;
}
Next i populated it with data using by spliting "cat" strings and pushing "ids" in loop (ex. some.category.sub.ids.push(7))
The final result was:
var output =
{
"some": {
"ids": [
"0",
"1"
],
"category": {
"ids": [
"2"
],
"sub": {
"ids": [
"3"
]
}
},
"other": {
"ids": [
"4"
]
},
"thing": {
"different": {
"ids": [
"5",
"6"
]
}
},
"yet": {
"another": {
"ids": [
"7"
]
}
}
}
}
However, the structure somewhat problematic because i don't know the key names and the nesting depth in advance.
How to generate nested html list out of "output" or "input" data presented here?
How about this?
Example
JS
function ToHTML(input){
var html = '<ul>';
for(var key in input){
if(input[key] instanceof Array){
for(var i = 0; i < input[key].length; i++){
html += '<li>' + input[key][i] + '</li>';
}
}else{
html += '<li>' + key + ToHTML(input[key]) + '</li>';
}
}
html += '</ul>';
return html;
}
function ToNestedObject(input){
var i, y, len = input.length, parts, partsLen, obj = {}, prev;
for(i = 0; i < len; i++){
parts = input[i].cat.split('/');
partsLen = parts.length;
prev = obj;
for(y = 0; y < partsLen; y++){
prev[parts[y]] = prev[parts[y]] || {};
prev = prev[parts[y]];
}
if(!prev.ids){
prev.ids = [];
}
prev.ids.push(input[i].id);
}
return obj;
}
var input= [
{
"cat": "some",
"id": "0"
},
{
"cat": "some",
"id": "1"
},
{
"cat": "some/category",
"id": "2"
},
{
"cat": "some/category/sub",
"id": "3"
},
{
"cat": "some/other",
"id": "4"
},
{
"cat": "some/thing/different",
"id": "5"
},
{
"cat": "some/thing/different",
"id": "6"
},
{
"cat": "yet/another",
"id": "7"
}
];
document.getElementById('test').innerHTML = ToHTML(ToNestedObject(input));
HTML
<div id='test'></div>
The array is converted into object tree
function buildTreeObject ( input ) {
var obj = {}, n ;
input.forEach( function( v ){
var keys = v.cat.split('/'),
n = obj ;
keys.forEach( function( k ){
if ( !n[k]) {
n[k] = {};
}
n = n[k];
});
n[ v.id ] = v.id ;
});
return obj;
}
and we need a function to build html
function buildHtml( obj , ul ) {
for (i in obj) {
var li = document.createElement('li');
li.innerHTML = i;
ul.appendChild( li );
if ( typeof(obj[i])== "object" ) {
childUl = document.createElement('ul');
li.appendChild( childUl );
buildHtml(obj[i], childUl );
}
}
}
and make html use of input ( ie ur array )
var ul = document.createElement('ul'),
tree = buildTreeObject( input ) ;
buildHtml( tree ,ul );
var div = document.createElement('div');
div.appendChild( ul );
console.log( div.innerHTML );
Which prints desired ul li list
You can see result in http://jsfiddle.net/r3RWL/
Since you added jquery under tags, I have written solution to your problem in jQuery. Here is the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div id="someDiv">
</div>
<script>
function prepareNestedStructure(input) {
var output = {},
catLevels,
currentCat;
$.each(input, function(index, catObject) {
catLevels = catObject.cat.split('/');
currentCat = output;
$.each(catLevels, function(index, name) {
if(!currentCat[name])
currentCat[name] = {};
currentCat = currentCat[name];
});
currentCat[catObject.id] = catObject.id;
});
return output;
}
function fillList(parentListEl, node) {
$.each(node, function(key, value) {
parentListEl.append('<li>' + key + '</li>');
if(jQuery.type(value) === 'object') {
var childEl = $('<ul></ul>');
parentListEl.append(childEl);
fillList(childEl, value);
}
});
}
var input= [
{
"cat": "some",
"id": "0"
},
{
"cat": "some",
"id": "1"
},
{
"cat": "some/category",
"id": "2"
},
{
"cat": "some/category/sub",
"id": "3"
},
{
"cat": "some/other",
"id": "4"
},
{
"cat": "some/thing/different",
"id": "5"
},
{
"cat": "some/thing/different",
"id": "6"
},
{
"cat": "yet/another",
"id": "7"
}
];
var output = prepareNestedStructure(input);
var ulDomElement = $('<ul></ul>');
fillList(ulDomElement, output);
$('#someDiv').append(ulDomElement);
</script>
</body>
</html>
what about this?
transform_deeply_nested_object = (dno) ->
result = ""
for key, value of dno
if value instanceof Array
result += "<ul>"
for elem in value
result += "<li>" + elem + "</li>\n"
result += "</ul>"
else
result += "<ul><li>" + key + "</li>"
result += transform_deeply_nested_object value
result += "</ul>"
Attention: Not tested!
Attention: This requires all leafs to be elements of an array always.