jQuery + table creation from json - javascript

I have a JSON file
{
"Scenario" : "ModelNameHere",
"id" : "1",
"description" : "Description of table model goes here",
"headers" : {
"Column 1 header" : {
"order" : 1,
"items" : {
"Row 1 Col 1 value" : {
"id" : 1,
"comment" : "Comment on Row 1 Col 1",
"order" : 1
},
"Row 2 Col 2 value" : {
"id" : 2,
"comment" : "Comment on Row 2 Col 2",
"order" : 2
}
}
},
"Column 2 header" : {
"order" : 2,
"items" : {
"Row 1 Col 2 value" : {
"id" : 3,
"comment" : "Comment on Row 1 Col 2",
"order" : 1
},
"Row 2 Col 2 value" : {
"id" : 4,
"comment" : "Comment on Row 2 Col 2",
"order" : 2
}
}
}
}
}
I want to use jQuery to put the JSON data into an HTML table.
Headers should go inside TH td items, items inside headers should be elements in the TD of each related row.
Is there a function in either JS or jQuery to populate a table with JSON data?
How would I loop through and match JSON elements to table elements?
Thanks.

No, there is no such function as it is a really situational specific function.
It's quite easy to write though.
You can acces the JSON as a normal JS object.
This means you can just loop trough it and put the information in the right spots.

This question explores various templating engines, which could help you with what you are trying to achieve. You would still need to define the template for the table, but populating it will be very easy.

Look at this plugin. There are many jQuery plugins so choose one that suits you.
http://www.datatables.net
Here is example from json, except that it is loaded from txt file but that is not problem.
http://www.datatables.net/examples/data_sources/ajax.html
And here is how I suggest you restructure your json. In my honest opinion you should think here in terms of tables and not objects.
{
"model" : "Model name here",
"id" : 1,
"description" : "Description of table model goes here",
"headers" : {
"header" : {
"id" : 1,
"order" : 1,
"name" : "Col 1 header name"
},
"header" : {
"id" : 2,
"order" : 3,
"name" : "Col 2 header name"
}
},
"row1" : {
"item" : {
"id" : 1,
"name" : "Some td data comes here"
},
"item2" : {
"id" : 4,
"name" : "Some td data comes here"
}
},
"row2" : {
"item" : {
"id" : 2,
"name" : "Some td data comes here"
},
"item2" : {
"id" : 3,
"name" : "Some td data comes here"
}
}
}

if u r doing in PHP then use json_decode('jsonstring',true);
that will comes as array and easily manipulate the array to create html

Related

Delete Document and all references in another Schema MongoDB

I have a schema for Forms and another one for Documents...
Each Document must have a reference _id of the Form that is related to,
so in database I can have many Documents with the same Form._id.
I want to know how to create a DELETE function for the Forms to do the following:
Find all Documents that have this Form._id and DELETE it all and then
delete the Form itself.
Ok, so lets start of with some basic forms and documents in our database
db.forms.insertMany([
{ _id : 1, name : "Form 1"},
{ _id : 2, name : "Form 2"}
]);
db.documents.insertMany([
{ _id : 1, formId : 1, name : "Doc 1" },
{ _id : 2, formId : 1, name : "Doc 2" },
{ _id : 3, formId : 1, name : "Doc 3" },
{ _id : 4, formId : 2, name : "Doc 4" }
])
> db.forms.find()
{ "_id" : 1, "name" : "Form 1" }
{ "_id" : 2, "name" : "Form 2" }
> db.documents.find()
{ "_id" : 1, "formId" : 1, "name" : "Doc 1" }
{ "_id" : 2, "formId" : 1, "name" : "Doc 2" }
{ "_id" : 3, "formId" : 1, "name" : "Doc 3" }
{ "_id" : 4, "formId" : 2, "name" : "Doc 4" }
Then we can create a simple function to pass in the form id and find and delete all the documents for that form id.
function removeForm(formId){
var ids = db.documents.find({ formId : formId}, { _id : 1 } ).map(function(doc){ return doc["_id"]; });
db.documents.remove( { "_id" : { "$in" : ids } } );
db.forms.remove( { "_id" : formId } );
}
Then we can call removeForm.
removeForm(1);
Then we'll see our documents and forms deleted
> db.forms.find()
{ "_id" : 2, "name" : "Form 2" }
> db.documents.find()
{ "_id" : 4, "formId" : 2, "name" : "Doc 4" }
In our application we do it like that:
When a user got deleted, delete also its corrosponding Scans & Categories
const scanModel = require("./Scan");
const categoryModel = require("./Category");
const userSchema = new mongoose.Schema({
...
})
userSchema.pre("remove", function(next) {
// 'this' is the user being removed. Provide callbacks here if you want
// to be notified of the calls' result.
scanModel.remove({ user: this._id }).exec();
categoryModel.remove({ user: this._id }).exec();
next();
});

printing the array under array in json file?

//I write a code of a json file in visual studio code....
let coll={
"collName" : "pu_vendor",
"collDesc" : "Vendor Master",
"formName" : "syscollection",
"formType" : "CRUD",
"docLevel" : [
{
"level" : 0,
"levelName" : "root",
"levelDesc" : "Vendor Description",
"parent" : "",
"comments" : "",
"fields" : [
{
"fieldName" : "vndrId",
"fieldDesc" : "Vendor ID",
"dataType" : "S",
"size" : 5,
"comments" : ""
}
]
}
]
}
i want to print all values with all keys type of key:value pattern....So i easily print with console.log
console.log(coll);
it shows truely all value by key:value pattern also but when it is comes on the next "fields" key, it prints only the type of this key i.e [Array], it do not show the keys and values of this key

ng-repeat: Dynamically generate anchor tag and corresponding HTML page for object

Currenty, I'm repeating a hundreds of items in an array like so:
<div ng-repeat="item in items | orderby:-Date">
<h3>{{post.Title}}</h3>
<h4>{{post.Company}}</h4>
<p>{{post.Description}}</p>
</div>
Which gets it's data from an object like this:
$scope.items = [
{
"ID" : "1",
"Title" : "A"
"Company" : "Company A",
"Date" : "2016-06-22",
"Description" : "..."
},{
"ID" : "2",
"Title" : "B"
"Company" : "Company B",
"Date" : "2016-06-23",
"Description" : "..."
},{
"ID" : "3",
"Title" : "C"
"Company" : "Company C",
"Date" : "2016-06-21",
"Description" : "..."
}
]
What I'd like to do is generate a unique link for each of the above as in .../items/1.html / .../items/2.html based on their ID and generate an html structure on that page that has the same structure as that of the ng-repeat div, but obviously without repeating.
Is this possible in javascript / angularJS or do I need to look into creating database entries with mySQL for each of these ID's?
I am not sure but as far as i know you cannot create html files using angularjs but if you want to show html pages that have same html template you can use it using states.
.state('post',{
url : '/post',
abstract : true,
templateUrl : 'some.html'
})
.state('post.id',{
url : '/{id}',
templateUrl : 'someHtml.html',
controller : 'PostController'
});
in controller you can get the id's as
app.controller('PostController',function($scope,$stateParams){
$scope.id = $stateParams.id;
});
you can call the posts, as
View Post
This will go to state /post/1 and so on depending on the ids from the json. Using the controller you can display your html of that particular post without needing to create physical html pages.

MongoDB .find() only ObjectId's embedded in an Array.

I am trying to get only the ObjectId's from One specific Document that is embedded in the projects Array.
Basically I am trying to make a database that will have users and each user will have there own projects.
Thank you !
db.users.find().pretty()
{
"_id" : ObjectId("5762c0cf2b9a78006373a684"),
"name" : "seq",
"pass" : "seq",
"projects" : [
{
"pid" : ObjectId("5762c0ba2b9a78006373a682"),
"name" : "aaa"
},
{
"pid" : ObjectId("5762c0ba2b9a78006373a683"),
"name" : "bbb"
}
]
}
{
"_id" : ObjectId("5762c28d2b9a78006373a687"),
"name" : "leq",
"pass" : "leq",
"projects" : [
{
"pid" : ObjectId("5762c2892b9a78006373a685"),
"name" : "ccc"
},
{
"pid" : ObjectId("5762c2892b9a78006373a686"),
"name" : "ddd"
}
]
}
let say we want two pids
{"pid" : ObjectId("5762c0ba2b9a78006373a682")} and
{"pid" : ObjectId("5762c2892b9a78006373a686"),}
and only inner documents
so required response should look like:
{
"_id" : ObjectId("5762c0ba2b9a78006373a682"),
"name" : "aaa"
},{
"_id" : ObjectId("5762c2892b9a78006373a686"),
"name" : "ddd"
}
Aggregation framework can manipulate documents, match only needed ones and transform inner structure by project phase:
var match = {
$match : {
"projects.pid" : {
$in : [ObjectId("5762c0ba2b9a78006373a682"),
ObjectId("5762c2892b9a78006373a686")]
}
}
}
var unwind = {
$unwind : "$projects"
};
// now move array objet as top level object
var project = {
$project : {
_id : "$projects.pid",
name : "$projects.name",
// list other fields here
}
}
db.vic.aggregate([match, unwind, match, project])

Meteor find is returning null with variable [duplicate]

This question already has an answer here:
Updating template with session variable and subscription/publication only updates with previous query and appends information
(1 answer)
Closed 7 years ago.
Description of the problem:
I have two collections videos and specs. videos collection has a key called spec which corresponds to a specs id. Both collections are not empty.
My Template Helper:
Template.List.helpers({
videos: function(){
var vids = Videos.find({ online: false}).fetch();
return vids.map(function(value){
console.log("id: " + value.spec);
console.log(Specs.find({ id: value.spec }).fetch());
//Issue here
value.specName = Specs.find({ id: value.spec }).fetch()[0].name;
return value;
});
}
});
As you can see in my template helper I loop through the video array and add specName to the array.
The main problem comes from this specific line:
value.specName = Specs.find({ id: value.spec }).fetch()[0].name;
and more specifically this line: Specs.find({ id: value.spec }).fetch()
which will return null every time.
What I've tried:
Naturally, my first thought would be to check what value.spec returns. And it returns an int between 1 and 15 (included) which is right. If value.spec is right, then how come the find() doesn't return anything?
I then decided to hard set it and tried this:
Specs.find({ id: 2}).fetch()
And this worked. Which is weird because on multiple occasions value.spec returns 2...
I've also tried intParse(value.spec) just in case, however that didn't work either.
Question
Why does Specs.find({ id: value.spec }).fetch() return null knowing that value.spec is set correctly and that a hard coded number works?
Requested json data: (from meteor mongo)
specs:
{ "_id" : "XKXHtQuiFsAew3dDy", "id" : 1, "name" : "Endocrine surgery" }
{ "_id" : "68jFidAMXTXpQtQye", "id" : 2, "name" : "General and digestive" }
{ "_id" : "GZSXToRXMfJgnH3CY", "id" : 3, "name" : "Pediatric surgery" }
{ "_id" : "T2mBz2gsXEqQaybmq", "id" : 4, "name" : "Thoracic surgery" }
{ "_id" : "hnuQzZiPKvYYDZhc8", "id" : 5, "name" : "Equipment" }
{ "_id" : "byE3A6HchvfhKdmR8", "id" : 6, "name" : "Gynecology" }
{ "_id" : "u5rrPB7asGW3NC6B2", "id" : 7, "name" : "Urology" }
{ "_id" : "umxKvR66oEx5dRppf", "id" : 8, "name" : "Cardiovascular surgery" }
{ "_id" : "bPcBTZn3t5ubRRcrQ", "id" : 9, "name" : "Endoscopic surgery" }
{ "_id" : "yNyAqQPoreNtdRZ34", "id" : 10, "name" : "NOTES" }
{ "_id" : "KG794eakRaztEqehG", "id" : 11, "name" : "Robotic surgery" }
{ "_id" : "QBrtvTg4GT7Tf7cAJ", "id" : 12, "name" : "Skull base surgery" }
{ "_id" : "HEhq6oBjuuMnrxE5a", "id" : 13, "name" : "Arthroscopy and upper limb surgery" }
{ "_id" : "xwpgHqZpBQP7WAnd5", "id" : 14, "name" : "Single port surgery" }
{ "_id" : "K4BgFupwNdDGD3449", "id" : 15, "name" : "Telemicrosurgery" }
videos:
{ "_id" : "L5Qi7YRRhn6Sfcjk8", "id" : "vd01en1065e", "title" : "Right inguinal hernia: open plug technique", "authors" : [ "E Pelissier" ], "date_published" : "2004-09-27", "abstract" : "", "tags" : [ "" ], "spec" : 2, "private" : true, "online" : false }
{ "_id" : "M8cuLW6KNCqKeP9vF", "id" : "vd01en1074e", "title" : "Laparoscopic splenectomy, posterior approach", "authors" : [ "D Mutter", " F Rubino" ], "date_published" : "2004-09-27", "abstract" : "", "tags" : [ "" ], "spec" : 2, "private" : true, "online" : false }
{ "_id" : "Ptzrxw8GifeMvQk9k", "id" : "vd01en1090e", "title" : "Intussusception of the intestine in the newborn", "authors" : [ "F Becmeur", " D Christmann", " I Kauffmann" ], "date_published" : "2004-09-27", "abstract" : "", "tags" : [ "" ], "spec" : 3, "private" : true, "online" : false }
{ "_id" : "oHWcX3vCBHuZQM9hR", "id" : "vd01en1103e_2", "title" : "Appendicular peritonitis: laparoscopic conversion", "authors" : [ "B Navez" ], "date_published" : "2001-11-05", "abstract" : "", "tags" : [ "" ], "spec" : 2, "private" : true, "online" : false }
{ "_id" : "6uzmxYxhd5DDuS2gG", "id" : "vd01en1108e", "title" : "Diaphragmatic hernias", "authors" : [ "F Becmeur" ], "date_published" : "2001-11-28", "abstract" : "", "tags" : [ "" ], "spec" : 3, "private" : true, "online" : false }
{ "_id" : "yHqruiQYeeQ9SDHpH", "id" : "vd01en1112e", "title" : "Laparoscopic excision of the cystic stump", "authors" : [ "J Leroy" ], "date_published" : "2004-09-27", "abstract" : "", "tags" : [ "" ], "spec" : 2, "private" : true, "online" : false}
{ "_id" : "fmjtk5WAEKitMxyGj", "id" : "vd01en1114e", "title" : "Laparoscopic gastric banding in a patient with a BMI of 40", "authors" : [ "JM Zimmermann", " D Fölscher" ], "date_published" : "2004-09-27", "abstract" : "", "tags" : [ "" ], "spec" : 2, "private" : true, "online" : false}
I've been stuck on this problem for a couple hours, I didn't want to post this on SO since I do believe it's a simple problem. However, it is mind boggling.
The problem here is the publication/subscription issue. You did not mention it, how do you handle publications and subscriptions but that is most likely the issue. What is happening is that when you browse your videos collection, which subscription is ready (since you hae any data in it) here: Videos.find({ online: false}) that not necessarly means that (in that precise moment) subscription handling Spec collection is ready as well. So even if on the server the query is working, on the client it's null, because the data are not synced between client and server YET. so you have to wait until both subscriptions are ready somehow. You can use template subscriptions, or waitOn function in your router.
First of all check on server side that your publication and subscription is ready and returning you back data check this like as
Meteor.publish('Videso', function () {
var result= Videso.find({});
console.log(result);
return result
});
if console.log returning you records on server side i have a solution then your
problem
the solution of your problem is that
Template.List.helpers({
videos: function(){
var vids = Videos.find({ online: false}).map(function (value) {
console.log("id: " + value.spec);
var idValue = Specs.findOne({ "id": value.spec })
console.log("idValue===",idValue)
return _.extend(value, idValue);
});
console.log(vids); //here merged data of both table having
// relvent record will returned
return vids;
}
});
Just implement it and check data on your template it will be ready for you and vote me then :)

Categories