JSON printing (treeview) - javascript

I have a complex json string that looks like this:
{
"id":"2016666",
"dt":"2012",
"object_extends":[
{
"extend1":{
"id":"2016666",
"dt":"2012",
"active":"true",
"object_extend":[
{
"extend2":
{
"id":"2016666",
"secondary":null
},
"extend3":
{
"id":"2016666",
"pet":"willy"
}
}
]
}
}
]
}
Now i want to print this like a tree, but when searching for days i have to modify the json(which is not a option). How can i print this in a treeview? I tried for loops but each extend can have other attributes then other objects. Hope somebody can help me with this!

Can you check these out:
How to generate Treeview from JSON data using javascript
https://github.com/lmenezes/json-tree
https://github.com/liuwenchao/aha-tree
https://github.com/AlexLibs/niTree
https://github.com/tamirs9876/JSON.Tree.Builder -- one of my fav
I think visit this and use which you like:
https://github.com/search?utf8=%E2%9C%93&q=json+tree&type=Repositories&ref=searchresults
Edit For Your Request :
To remove the null nodes in https://github.com/tamirs9876/JSON.Tree.Builder -- one of my fav :
Cover line 8 with
if(data[i] != null){
}
in JsonTreeBuilder.js
Last state of js file is like
.
.
var ul = $('<ul>');
for (var i in data) {
var li = $('<li>');
if(data[i] != null){
ul.append(li.text(i).append(generateTree(data[i])));
}
}
.
.

Related

Dynamic query to take input from user and do filtering from the database node.js

enter image description hereWhat I'm trying is fetching columns from the user to which the user entered, The Good thing is Columns are getting fetched and the bad thing is the columns that I had applied conditions are not working.Can anyone help me out? I want a query that works for the filter option as in many websites to filter any product or something.
Newbie here!!!
routes.post('/FilterCandidate',function(req,res){
var fetchparameter={};
var dynamicquery={author : req.user.username};
if(req.user.username){
if(req.body.ConsultantName){
fetchparameter["ConsultantName"] = req.body.ConsultantName;
}
if(req.body.Location){
fetchparameter["Location"] = req.body.Location;
}
if(req.body.JobRole){
fetchparameter["JobRole"] = req.body.JobRole;
}
if(req.body.Skills){
fetchparameter["Skills"] = req.body.Skills.split(',');
}
if(req.body.VisaStatus){
fetchparameter["VisaStatus"] = req.body.VisaStatus;
}
if(req.body.BillingRate){
fetchparameter["BillingRate"] = req.body.BillingRate;
}
if(req.body.experience){
fetchparameter["experience"] = req.body.experience;
}
if(req.body.jobtype){
fetchparameter["jobtype"] = req.body.jobtype;
}
if(req.body.Availability){
fetchparameter["Availability"] = req.body.Availability;
}
if(req.body.experience){
fetchparameter["Salary"] = req.body.Salary;
}
if(req.body.Salarytype){
fetchparameter["Salarytype"] = req.body.Salarytype;
}
}
/* This below code for conditions is not working*/
for(var key in fetchparameter){
if (key== "Salary" ){
dynamicquery[key] = {$gte :fetchparameter[key]};
}
if(key == "Skills"){
dynamicquery [key] = {$in : fetchparameter[key]};
}
if(key == "experience"){
dynamicquery[key] = {$gte :fetchparameter[key]};
}
else{
dynamicquery[key] = fetchparameter[key];
}
}
console.log(dynamicquery);
Candidate.aggregate([ {$match : dynamicquery }],(err,docs) =>{
res.render('FilteredCandidate',{'Candidates' : docs});
});
});
This is what I'm getting output to refer to the attached image
i think you should make a match object array it will make your code more neat and hoping that it will solve your problem
Ex:
var match = {$and:[]};
if(any condition satisfy){
match.$and.push({}) //condition
}
and most important do check if match.$and array must not be empty if it is then delete match.$and. this procedure will help you to maintain your query better provides more flexibility.

Angular Chosen default not working with object

I am using https://github.com/localytics/angular-chosen to allow for select tags with search capability for many options.
The problem I'm having is with preselecting an option on an already saved vendor object. When creating a new one there is now issue, but if we're viewing an existing vendor, I want to show the vendor's name in the select box, rather than the placeholder.
<select chosen
ng-model="myVendor"
ng-options="vendor['public-id'] as vendor.name for vendor in vendors"
data-placeholder="Nah">
</select>
And in my controller, I'm setting the model by hand $scope.myVendor = "Some value"
The problem is that I'm populating the options with an object, instead of a key/value. I found an example of it working with a key/value, but haven't had success adapting this to objects as options.
I've even tried setting myVendor to the matching object that I want selected, with no luck.
Plunker of issue
I updated the plunker and change my previous changes on the plugin. this was not the issue. I don't understand how it was giving me errors there.
The solution is to track with an object and two functions the id and the name:
// Controller
$scope.vendors = [
{
"public-id": "1234",
"name": "stugg"
},
{
"public-id": "4321",
"name": "pugg"
}
];
$scope.myVendor = {name: "pugg", id:""};
$scope.updateMyVendorName = function () {
var found = false,
i = 0;
while (!found && i < $scope.vendors.length) {
found = $scope.vendors[i]['public-id'] === $scope.myVendor.id;
if (found) {
$scope.myVendor.name = $scope.vendors[i].name;
}
i++;
}
}
findVendorByName();
function findVendorByName () {
var found = false,
i = 0;
while (!found && i < $scope.vendors.length) {
found = $scope.vendors[i]['name'] === $scope.myVendor.name;
if (found) {
$scope.myVendor.id = $scope.vendors[i]['public-id'];
}
i++;
}
}
// template
<select chosen class="form-control span6" ng-options="vendor['public-id'] as vendor.name for vendor in vendors" ng-model="myVendor.id" ng-change="updateMyVendorName()">
{{myVendor.name}}

how to get json data with the following format?

I've a json file to get a list of test results.
Below is the json file. And a short snippet of the jquery.
I am trying to get the test id from the json and display them as a unordered list.
How can I do that?
[
{
"Test":{
"id":"2949",
"bk_session_id":"qpmz3gd6xw",
"series_type":"Cars Series",
"book_type":"A",
}
},
{
"Test":{
"id":"2950",
"bk_session_id":"qpmz3gd6xw",
"series_type":"Cars Series",
"book_type":"A",
}
}
]
<script type="text/javascript">
$.getJSON("http://localhost:8888/tests/students.json?id=qpmz3gd6xw", function(data) {
for (var i in data)
{
alert(data[i].[Test].id);
}
});
</script>
You're missing the quotes around Test, it should be a string and remove the dot before it.
alert(data[i]['Test'].id);
also your json is not valid, remove the trailing , after each book_type.
[
{
"Test":{
"id":"2949",
"bk_session_id":"qpmz3gd6xw",
"series_type":"Cars Series",
"book_type":"A"
}
},
{
"Test":{
"id":"2950",
"bk_session_id":"qpmz3gd6xw",
"series_type":"Cars Series",
"book_type":"A"
}
}
]
http://jsfiddle.net/ef7Nq/
Loop through the items in the array and append nodes for each id.
$.each(obj, function (i, item) {
ul.append($('<li>' + item.Test.id + '</li>'));
});
fiddle here
You can do data[i]['Test'].id or data[i].Test.id since there's no space in the name.
You can try this:
alert( data[i].Test.id );
Full Code:
$.getJSON("http://localhost:8888/tests/students.json?id=qpmz3gd6xw", function(data) {
for (var i in data) {
alert( data[i].Test.id );
}
});
Demo
Try
Fiddle Demo
var ul = '';
for (var i in data)
{
ul += '<li>'+data[i]['Test'].id+'</li>';
}
$('#el').append($('<ul/>').html(ul));

Shorten function in Javascript / Jquery

LF way to short my js/jquery function:
$.ajax({ // Start ajax post
..........
success: function (data) { // on Success statment start
..........
//1. Part
$('var#address').text(data.address);
$('var#telephone').text(data.telephone);
$('var#mobile').text(data.mobile);
$('var#fax').text(data.fax);
$('var#email').text(data.email);
$('var#webpage').text(data.webpage);
//2. Part
if (!data.address){ $('p#address').hide(); } else { $('p#address').show(); };
if (!data.telephone){ $('p#telephone').hide(); } else { $('p#telephone').show(); };
if (!data.mobile){ $('p#mobile').hide(); } else { $('p#mobile').show(); };
if (!data.fax){ $('p#fax').hide(); } else { $('p#fax').show(); };
if (!data.email){ $('p#email').hide(); } else { $('p#email').show(); };
if (!data.webpage){ $('p#webpage').hide(); } else { $('p#webpage').show(); };
}, End Ajax post success statement
Here is my html:
<p id="address">Address:<var id="address">Test Street 999 2324233</var></p>
<p id="telephone">Telephone:<var id="telephone">+1 0000009</var></p>
<p id="mobile">Mobile:<var id="mobile">+1 0000009</var></p>
<p id="email">E-mail:<var id="email">info#example</var></p>
<p id="webpage">Web Page:<var id="webpage">www.example.com</var>/p>
How can we reduce the number of selector*(1. part)* and else if the amount (2. part)?
Assuming your object's property names exactly match the spelling of your element ids you can do this:
for (var k in data) {
$('var#' + k).text(data[k]);
$('p#' + k).toggle(!!data[k]);
}
...because .toggle() accepts a boolean to say whether to show or hide. Any properties that don't have a matching element id would have no effect.
Note: your html is invalid if you have multiple elements with the same ids, but it will still work because your selectors specify the tag and id. Still, it might be tidier to just remove the ids from the var elements:
<p id="address">Address:<var>Test Street 999 2324233</var></p>
<!-- etc. -->
With this JS:
$('#' + k).toggle(!!data[k]).find('var').text(data[k]);
And then adding some code to hide any elements that aren't in the returned data object:
$('var').parent('p').hide();
...and putting it all together:
$.ajax({
// other ajax params here
success : function(data) {
$('var').parent('p').hide();
for (var k in data) {
$('#' + k).toggle(!!data[k]).find('var').text(data[k]);
}
}
});
Demo: http://jsfiddle.net/z98cw/1/
["address", "telephone", "mobile", "fax", "email", "webpage"].map(
function(key) {
if (data.hasOwnProperty(key) && !!data[key]) {
$('p#' + key).show();
} else {
$('p#' + key).hide();
}
});
But you should not.
As long as the properties of the object match the id attributes of the p tags you can iterate through the object using the property name as a selector. Also since id attributes are unique, refrain from prefixing the selector with var it is unnecessary.
var data = {
address: "address",
telephone: "telephone",
mobile: "mobile",
fax: "fax",
email: "email",
webpage: "webpage"
};
for(x in data){
var elem = $("#" + x);
if(elem.length == 1){
elem.text(data[x]);
}
}
JS Fiddle: http://jsfiddle.net/3uhx6/
This is what templating systems are created for.
If you insist on using jQuery there is a jQuery plugin: https://github.com/codepb/jquery-template
More:
What Javascript Template Engines you recommend?
I would use javascript templates for this (I've shortened the example a quite a bit, but you should get the gist).
First the template, I love Underscore.js for this so I gonna go ahead and use that.
<% if data.address %>
<p id="address">Address: {%= Test Street 999 2324233 %}</p>
to compile this inside your success function
success: function(data) {
//assuming data is a json that looks like this {'address':'my street'}
var template = _.template(path_to_your_template, data);
$('var#addresscontainer').html(template);
}
Thanks for birukaze and nnnnnn:
With your advice came function;) :
for (var key in data) {
if (data.hasOwnProperty(key) && !!data[key]) {
$('p#' + key).show().find('var').text(data[key]);
} else {
$('p#' + key).hide();
}
};
Now i can avoid for selector with var.

Create List input checked array for posting REST API

I've used .push() to create "List" input checked array for posting REST API. But it doesn't seem right.
When unchecking, the item in array is not removed automatically. Anybody have a better solution, pls help me! Tks
http://plnkr.co/edit/Y0YggxvVN1epIMWAdtiU?p=preview
You could do this... it works. Can't say this is the best solution though
$scope.$watch('lists', function(lists){
$scope.count = 0;
angular.forEach(lists, function(list){
if(list.checked){
$scope.count += 1;
if (inputsList.indexOf(list.id) == -1) {
inputsList.push(list.id);
};
} else {
inputsList.pop(list.id);
}
})
}, true);
Same logic, but, modified a lil
index.html (added ng-click)
<input type="checkbox" name="list_id[]" ng-model="list.checked" value="{{list.id}}" ng-click='updateItem(list)' />
app.js (removed $scope.$watch and...)
$scope.currentSelectedItem = [];
$scope.updateItem = function(item) {
if(item.checked) {
$scope.currentSelectedItem.push(item);
} else {
$scope.currentSelectedItem.pop(item);
}
}

Categories