jQuery JSON looping through nested objects - javascript

I currently have this:
$.getJSON('test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
test.json looks like this:
{"key1":{"key11":"value11","key12":"value12"},"key2":"value2","key3":"value3"}
I'm getting:
[object Object]
value2
value3
How can I change it so it will loop through all the nested items regardless of how many nested values I have?
So for the above example I will get
value1
value11
value12
value2
value3

You can make a recursive loop function, but you'd have a problem: when a property is an object, there is no text to display because there is no string. So, you'll end up with:
- - value11
- value12
- value2
- value3
because while value2 is the string to display for item #2, it is an object that's displayed for item #1.
Anyway, this is what I made up: http://jsfiddle.net/uXww2/.
// obj is the object to loop, ul is the ul to append lis to
function loop(obj, ul) {
$.each(obj, function(key, val) {
if(val && typeof val === "object") { // object, call recursively
var ul2 = $("<ul>").appendTo(
$("<li>").appendTo(ul)
);
loop(val, ul2);
} else {
$("<li>", {
id: key
}).text(val).appendTo(ul);
}
});
}
$.getJSON('test.json', function(data) {
var ul = $("<ul>");
loop(data, ul);
ul.addClass("my-new-list").appendTo('body');
});

so, what you want is a treeview looping through a json object
you can use this code i made myself recursively, test it ;)
var treestring = "";
var myid = "arv";
var json_object = {your json};
var Tree = function (data) {
this.data = data;
};
//1st step
Tree.renderTree(json_object, myid);
//2st step , this is a function
Tree.renderTree= function (json_object, myid) {
$.each(json_object, function (key, val) {
var m = new Tree(val);
m.render(myid);
});
}
//3st step, this a function too
Tree.prototype.render = function (myid) {
treestring = "<li class='category'> " + this.data.Name;
//Check if has another arrays inside the current
if (this.data.SubFolders) {
treestring += "<ul id=" + this.data.ID + "</ul>";
$("#" + myid).append(treestring);
myid = this.data.ID;
Tree.renderTree(this.data.Sub_Fodlers, myid);
}
else {
treestring += "</li>";
$("#" + myid).append(treestring);
}
};
//HTML
<div id="tree">
<ul id="arv"></ul>
</div>
//this.data.{something} ate the fields defined in your json object
enjoy ;)

Related

Datatable : Highlight a different cell from the others on a row

I would like on the same line to find the cell different from the others and to highlight it by a CSS class. Here is what I would like to do:
What I don't know is how to find the different data, I think I have to loop the line but then I get stuck.
JsFiddle DEMO
function constructRaws(data) {
var raws = [];
$.each(data, function(i, value) {
$.each(value, function(ind, val){
console.log(val);
value[ind] = "<span>"+val+"</span>" + "<span class='tdtooltip' style='display:none'>"+ val +"<span class='spid' style='display:none'>0</span></span>";
if (typeof val === "object"){
value[ind] = "<span>"+val[0]+"</span>" + "<span class='tdtooltip' style='display:none'>"+ obj_to_string(val) + "<span class='spid' style='display:none'>"+ val[1] +"</span></span>";
}
});
raws.push($.extend(value, {service: i}));
});
return raws;
}

Append returned data to different elements based on objects names

How do you append json returned objects to different elements based on the object's name? My JSON data is bigger than the following example so I wonder if it's a good idea to use if statement in .ajax for each object:
JSON Example Data
[{"name":"Europe","year":"2000"},{"name":"Asia","year":"2001"},{"name":"Africa","year":"2002"}]
HTML
<div class="Europe"></div>
<div class="Asia"></div>
<div class="Africa"></div>
JS
$.ajax({
url: "text.json",
success: function (data) {
var item_html;
$(data).each(function (index, item) {
var name = item.name;
item_html='<h3>'+name+'</h3><div>'+item.year+'</div>';
});
if (name == Africa){
$('.Africa').append(item_html);
}
if (name == Europe){
$('.Europe').append(item_html);
}
if (name == Asia){
$('.Asia').append(item_html);
}
},
error: function () {$('.Europe').append("<b>No Results Returned</b>");}
});
Move your if block in each
$(data).each(function (index, item) {
var name = item.name;
item_html = '<h3>' + name + '</h3><div>' + item.year + '</div>';
if(name == 'Africa') {
$('.Africa').append(item_html);
}
if(name == 'Europe') {
$('.Europe').append(item_html);
}
if(name == 'Asia') {
$('.Asia').append(item_html);
}
});
I think since the name and class names are the same you can use it to find the target element within the .each() loop and set its content like
$.ajax({
url: "text.json",
success: function (data) {
var item_html;
$(data).each(function (index, item) {
var name = item.name;
$('.' + name).html('<h3>' + name + '</h3><div>' + item.year + '</div>')
});
},
error: function () {
$('.Europe').append("<b>No Results Returned</b>");
}
});

Can't return only usernames from json data fetched through a php page

I am able to get json data from an external php page and print it on the JavaScript console. But these are in the form objects. The following is the data I recieved on my console:
[{"id":"1","username":"iammuneeb","password":"4297f44b13955235245b2497399d7a93","name":"Mirza Muneeb"},{"id":"2","username":"iamfaiz","password":"4297f44b13955235245b2497399d7a93","name":"Faiz"}]
How can I extract only username and turn it into an ordered list. (ol)
This is what I have done so far:
$(document).ready(function (e) {
$('#delete').click(function (e) {
var jsonData = getResultsInJson(username);
jsonData.success(function (data) {
var output = "<ol>";
for (var i in data) {
output += "<li>" + data.username + "</li>";
}
output += "</ol>";
$('#placeholder').html(data);
console.log(data.username);
});
});
});
This is getResultsInJson():
function getResultsInJson(sql) {
return $.ajax({
url: 'commands.php',
data: 'results=' + sql,
dataType: 'json'
});
}
when you use the for(x in y) format, x is the key, and y is the array or object. Since i is just the key, you need to use it as one:
for (var i in data) {
output += "<li>" + data[i].username + "</li>";
}
Do you need them in alphabetically?
Try something like this:
$(document).ready(function() {
var json = [{"id":"1","username":"iammuneeb","password":"4297f44b13955235245b2497399d7a93","name":"Mirza Muneeb"},{"id":"2","username":"iamfaiz","password":"4297f44b13955235245b2497399d7a93","name":"Faiz"}];
var usernames = new Array();
$.each(json, function(index, object) {
usernames[index] = object.username;
});
var sorted = usernames.sort();
var output = '';
$.each(sorted, function(index, value) {
output += '<li>' + value + '</li>';
});
$('#placeholder').html('<ol>' + output + '</ol>');
});

Can't create select element with returned json data from Ajax call

I'm making an ajax call to retrieve some JSON objects. I get them right. but the problem is when I want to create a select element from returned JSON, it doesn't create one or seemed to be.
My JavaScript so far:
jQuery("#make").change(function () {
var value = $(this).val();
jQuery.getJSON("<?php echo site_url('ajax/get/models'); ?>", {
makeId: value
},
function (data) {
if (data != "false") {
var modelsSelect = jQuery.createElement('select');
var modelsOptions = "";
var id;
var model
jQuery.each(data, function () {
jQuery.each(this, function (key, value) {
if (key == "id") {
id = value;
} else {
model = value;
}
});
modelsOptions += "<option value=" + id + ">" + model + "</option>"
});
modelsSelect.innerHTML = modelsOptions;
jQuery("#model").html = modelsSelect;
} else {
alert("false");
}
});
});
my returned JSON Format:
Object { id="28", model="test model"}
There could be n number of JSON objects in returned response from ajax call.
There is no createElement method in jQuery
jQuery.createElement should be document.createElement
Also no need to loop over the objects' properties, you can access them by the key directly
jQuery.each(data, function (index, item) {
modelsOptions += "<option value=" + item.id + ">" + item.model + "</option>"
});
Change this
jQuery("#model").html = modelsSelect;
to
jQuery("#model").html(modelsSelect);
Reference
.html()

search with an array associate with javascript?

I want to do a search by name and surname with an array javascript, and the results in a div. for example: I write Ali in input, an it shoul show me Alison and Alibaba.
this is my code, but it's giving errors; are there other ways to do it?:
<input type='text' id='filter' placeholder='search'>
<div id='output' style='margin-top:50px '></div>
my array
var arrayD =[
{"Name":"Alison","Surname":"Kenn","Mobile":529129293},
{"Name":"Ashton","Surname":"Jhojan","Mobile":529129293},
{"Name":"Bith","Surname":"Klint","Mobile":129129293},
{"Name":"Ana","Surname":"Clow","Mobile":229129293},
{"Name":"Geoge","Surname":"Rich","Mobile":329129293},
{"Name":"kenneth","Surname":"Cooler","Mobile":329129}
]
var $result = $('#output');
$('#filter').on('keyup', function () {
var $fragment = $('<div />');
var val = this.value.toLowerCase();
$.each(arrayD, function (i, item) {
console.log( item[0].toLowerCase().indexOf(val));
if ( item[0].toLowerCase().indexOf(val) == 0 ) {
$fragment.append('<li>' + item[0] + ' ' + item[1] + '</li>');
}
});
$result.html( $fragment.children() );
});
http://jsfiddle.net/henrykend/ChpgZ/4/
The main problem with your code is that you're trying to reference fields in the object by ordinal position rather than name. There is nothing automagic in JavaScript which will read item.Name (or item["Name"]) from item[0].
There is also no need to build up a "false element" (in your case $fragment) and then append its children to the output area - you may as well do this in one go (remembering to .empty() it between calls).
Your corrected code:
var $result = $('#result');
$('#output').on('keyup', function () {
$result.empty();
var val = this.value.toLowerCase();
$.each(arrayD, function (i, item) {
if ( item.Name.toLowerCase().indexOf(val) == 0 ) {
$result.append('<li>' + item.Name + ' ' + item.Surname + '</li>');
}
});
});
And a live example: http://jsfiddle.net/ChpgZ/6/
You had couple of problems in your code.
Names of the elements we're wrongly placed (which you've fixed with the edit)
In the .each, you've used item[0] instead of item.Name (also surname)
See the following code
var arrayD =[
{"Name":"Alison","Surname":"Kenn","Mobile":529129293},
{"Name":"Ashton","Surname":"Jhojan","Mobile":529129293},
{"Name":"Bith","Surname":"Klint","Mobile":129129293},
{"Name":"Ana","Surname":"Clow","Mobile":229129293},
{"Name":"Geoge","Surname":"Rich","Mobile":329129293},
{"Name":"kenneth","Surname":"Cooler","Mobile":329129}
]
var $result = $('#result');
$('#output').on('keyup', function () {
var $fragment = $('<div />');
var val = this.value.toLowerCase();
$.each(arrayD, function (i, item) {console.log( item.Name.toLowerCase().indexOf(val) );
if ( item.Name.toLowerCase().indexOf(val) == 0 ) {
$fragment.append('<li>' + item.Name + ' ' + item.Surname + '</li>');
}
});
$result.html( $fragment.children() );
});

Categories