I'm trying to create a nested listed view with jQuery. The data is in a json file.
Looks like this:
{
"fakultaeten": [
{
"id": "1",
"name": "Carl-Friedrich Gauß",
"institut": [
"Mathematik",
"Informatik"
]
},
{
"id": "2",
"name": "Lebenswissenschaften",
"institut": [
"Biologie/Biotechnologie",
"Chemie/Lebensmittelchemie"
]
},
{
"id": "3",
"name": "Architektur, Bauingenieurwesen und Umweltwissenschaften",
"institut": [
"Department Architektur",
"Department Bauingenieurwesen und Umweltwissenschaften"
]
},
{
"id": "4",
"name": "Maschinenbau",
"institut": [
"test"
]
},
{
"id": "5",
"name": "Elektrotechnik, Informationstechnik, Physik",
"institut": [
"Institut für Datentechnik und Kommunikationsnetze",
"Institut für Elektrische Maschinen, Antriebe und Bahnen"
]
},
{
"id": "6",
"name": "Geistes- und Erziehungswissenschaften",
"institut": [
"test"
]
}
]
}
I'm calling the data like this:
<script type="text/javascript" charset="utf-8">
$.getJSON("fakultaeten.js",function(data)
{
$.each(data.fakultaeten, function(key,value)
{
$.each(value.institut, function(key1,value1)
{
//console.log(value1)
}
);
}
);
return false;
}
);
</script>
Now I'm a little confused how to display the data in this HTML code.
<div data-role="content">
<h3>Institut für Nachrichtentechnik</h3>
<ul id="taskList" data-role="listview"></ul>
</div>
I know it's a basic problem, but all the other questions and tutorials I found are really confusing me.
I want the nested list look like in this demo: http://jquerymobile.com/demos/1.2.1/docs/lists/lists-nested.html#&ui-page=2-4
it's very simple: just put list value inside the list with id taskList:
<script type="text/javascript" charset="utf-8">
$.getJSON("fakultaeten.js",function(data)
{
var list = $('#taskList');
$.each(data.fakultaeten, function(key,value)
{
var mother = "<li>"+value.name+"<ul>";
$.each(value.institut, function(key1,value1)
{
var son="<li>"+value1+"</li>";
mother+=son;
}
);
mother+="</ul></li>";
list.append(mother);
}
);
list.listview("refresh");
return false;
}
);
</script>
Thanks to #JackTurky I got the solution. He was almost right.
This is how I solved it in the end.
<script type="text/javascript" charset="utf-8">
$.getJSON("fakultaeten.js",function(data)
{
var list = $('#taskList');
$.each(data.fakultaeten, function(key,value)
{
var mother = "<li>"+value.name+"<ul>";
$.each(value.institut, function(key1,value1)
{
var son="<li>"+value1+"</li>";
mother+=son;
}
);
mother+="</ul></li>";
list.append(mother);
}
);
list.listview("refresh");
return false;
}
);
</script>
Related
I'm trying to create a D3 Force-Directed Graph variant I found here https://github.com/vasturiano/3d-force-graph using JSON data on 30,000+ Steam Games.
I'd like to link games by their first 'steamspy_tags' which requires converting this data to nodes and links like so
{ "nodes": [
{"id": "Myriel", "group": 1},
{"id": "Napoleon", "group": 1}],
"links": [
{"source": "Napoleon", "target": "Myriel", "value": 1},
{"source": "Mlle.Baptistine", "target": "Myriel", "value": 8}
Is there an easy way to convert raw JSON to node and link data to format it for the graph?
The data is structured like so:
[
{
"appid": 10,
"name": "Counter-Strike",
"developer": "Valve",
"categories": "Multi-player;Online Multi-Player;Local Multi-Player;Valve Anti-Cheat enabled",
"genres": "Action",
"steamspy_tags": "Action;FPS;Multiplayer"
},
{
"appid": 20,
"name": "Team Fortress Classic",
"developer": "Valve",
"categories": "Multi-player;Online Multi-Player;Local Multi-Player;Valve Anti-Cheat enabled",
"genres": "Action",
"steamspy_tags": "Action;FPS;Multiplayer"
},
The graph code itself is as follows:
<head>
<style> body { margin: 0; } </style>
<script src="//unpkg.com/element-resize-detector/dist/element-resize-detector.min.js"></script>
<script src="//unpkg.com/3d-force-graph"></script>
<!-- <script src="../../dist/3d-force-graph.js"></script>-->
</head>
<body>
<div id="3d-graph"></div>
<script type="module">
import { UnrealBloomPass } from '//unpkg.com/three/examples/jsm/postprocessing/UnrealBloomPass.js';
const elem = document.getElementById('3d-graph');
const Graph = ForceGraph3D()(elem)
.jsonUrl('../datasets/developers/valve.json')
.nodeAutoColorBy('maintag')
.nodeVal('PosRat')
.backgroundColor('#171717')
.cooldownTicks(100)
.height(window.innerHeight - 60)
.nodeLabel(node => `${node.title}: ${node.release_date}: ${node.maintag}`)
.onNodeHover(node => elem.style.cursor = node ? 'pointer' : null)
.onNodeClick(node => window.open(`https://store.steampowered.com/app/${node.id}`, '_blank'));
const bloomPass = new UnrealBloomPass();
bloomPass.strength = 1.0;
bloomPass.radius = 0.3;
bloomPass.threshold = 0.25;
Graph.postProcessingComposer().addPass(bloomPass);
Graph.onEngineStop(() => Graph.zoomToFit(400));
</script>
</body>
I am still learning Vue.js. At the moment I am trying to make a simple filtered list method that pulls the data from a json file in Vue. I think that I am having trouble figuring out the correct syntax.
I just cant seem to get it right. Any help is more than welcome :)
This is Vue file:
<template>
<section>
<ul>
<li v-for="product in rings" :key="product">
{{product.title}}
</li>
</ul>
</section>
</template>
<script>
import data from '#/assets/data.json';
export default {
data() {
return {
products: []
}
},
methods: {
computed: {
rings(){
return this.products.filter(product => product.type == 'Ring')
}
}
}
}
</script>
And this is the Json file:
{ "products": [
{
"title": "Ring 1",
"description": "something",
"type": "Ring",
"year": "2018",
"image": "...",
"price": "2000,00 kr."
},
{
"title": "Halskæde 1",
"description": "something",
"type": "Halskæde",
"year": "2018",
"image": "...",
"price": "2000,00 kr."
},
{
"title": "Armbånd 1",
"description": "something",
"type": "Armbånd",
"year": "2018",
"image": "...",
"price": "2000,00 kr."
},
{
"title": "Ørering 1",
"description": "something",
"type": "Ørering",
"year": "2018",
"image": "...",
"price": "2000,00 kr."
}
]
}
You imported the data but never used anywhere inside the component:
import data from '#/assets/data.json';
// notice the data here is just a variable and it has nothing to do with the
// component's data property
export default {
data () {
return {
products: data.products // init products with imported data
}
},
Or with the destructuring syntax:
import { products } from '#/assets/data.json';
export default {
data () {
return {
products // init products with imported data
}
},
I need to access the values of "city" and "nation" inside the array the following json file using AngularJS with ng-repeat.
This is my Json file:
[
{
"name": "first",
"location": [
{
"city" : "milan",
"nation" : "italy"
}
],
"visibility": 1
},
{
"name": "second",
"location": [
{
"city" : "new york",
"nation" : "usa"
},
{
"city" : "london",
"nation" : "uk"
}
],
"visibility": 1
}
]
My problem is that I need to get City and Nation as text string values, because I need to add them as css class name inside a tag, basically like this:
<div class="milan italy"></div>
<div class="new york usa london uk></div>
I'm not able to figure it out how to do this.
I tried with this code but nothing is shown:
<div ng-repeat-start="tile in tiles"></div>
<div class="mix {{ tile.location.city }} {{ tile.location.nation }}"></div>
<div ng-repeat-end></div>
Thank you in advance for your suggestions.
As #MattDionis said, you would need to specify ng-class, not just class. What you can try is using a function for ng-class. So you can do
<div ng-repeat="tile in tiles">
<div ng-class="getLocation(tile)"></div>
</div>
$scope.getLocation = function(tile) {
var resp = '';
for (var i = tile.location.length; i-- > 0;) {
resp = resp + tile.location[i].city + ' ' + tile.location[i].nation;
}
return resp;
}
I'm sure there's a better way to combine them than that, but that's what I came up with off-hand
First, you want to use ng-class rather than simply class to properly evaluate those bindings.
Also, tile.location appears to be an array of objects rather than simply an object. Therefore, {{ tile.location.city }} would not work, but {{ tile.location[0].city }} should.
The remaining issue would be how to loop through mutliple city/nation values within ng-class. I'll get back to you on that.
Please see demo below
You can create function to transform your array of object to string ie:
$scope.tostring = function (array) {
var res = "";
angular.forEach(array, function (obj) {
console.log(obj);
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
res += " " +obj[k];
}
}
});
return res;
};
var app = angular.module('app', []);
angular.module('app').controller('homeCtrl', homeCtrl);
homeCtrl.inject = ['$scope'];
function homeCtrl($scope) {
$scope.titles = [{
"name": "first",
"location": [{
"city": "milan",
"nation": "italy"
}],
"visibility": 1
}, {
"name": "second",
"location": [{
"city": "new york",
"nation": "usa"
}, {
"city": "london",
"nation": "uk"
}
],
"visibility": 1
}];
$scope.tostring = function(array) {
var res = "";
angular.forEach(array, function(obj) {
console.log(obj);
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
res += " " + obj[k];
}
}
});
return res;
};
}
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-controller="homeCtrl">
<div ng-repeat="title in titles">
<h3 ng-class="tostring(title.location)">{{title.name}} My class is:*{{tostring(title.location)}}* </h3>
</div>
</body>
</html>
I have a collection of items. The items are broken down into "types" and then further divided within the type into "categories". I do not know the names of the "types" or the "categories" before hand.
I would like to do some nested foreach binding to represent the data hierarchically. Something like this:
<ul data-bind="foreach: OrderItems.Types">
<li>
ItemType: <span data-bind='text: $data'></span>
<ul data-bind="foreach: Categories">
<li>
Category: <span data-bind='text: $data'></span>
<ul data-bind="foreach: OrderItems">
<li>
Item: <span data-bind="text: Name"> </span>
</li>
</ul>
</li>
</ul>
</li>
var order = {
"OrderNumber": "394857",
"OrderItems": {
"Types": {
"Services": {
"Categories": {
"carpet cleaning": {
"OrderItems": [
{
"OrderItemID": "9d398f88-892c-11e3-8f31-18037335d26a",
"Name": "ARug-Oriental Rugs (estimate on site)"
},
{
"OrderItemID": "9d398f53-892c-11e3-8f31-18037335d26a",
"Name": "C1-Basic Cleaning (per room)"
},
{
"OrderItemID": "9d398f54-892c-11e3-8f31-18037335d26a",
"Name": "C2-Clean & Protect (per room)"
},
{
"OrderItemID": "9d398f55-892c-11e3-8f31-18037335d26a",
"Name": "C3-Healthy Home Package (per room)"
}
]
},
"specialty": {
"OrderItems": [
{
"OrderItemID": "9d398f8f-892c-11e3-8f31-18037335d26a",
"Name": "SOTHR-Other"
}
]
},
"tile & stone": {
"OrderItems": [
{
"OrderItemID": "9d398f8e-892c-11e3-8f31-18037335d26a",
"Name": "TILE-Tile & Stone Care"
}
]
},
"upholstery": {
"OrderItems": [
{
"OrderItemID": "9d398f7b-892c-11e3-8f31-18037335d26a",
"Name": "U3S1-Upholstery - Sofa (Seats 3: 7 linear feet)"
},
{
"OrderItemID": "9d398f7c-892c-11e3-8f31-18037335d26a",
"Name": "U3S2-Upholstery - Sofa - Clean & Protect (Seats 3: 7 linear feet"
}
]
}
}
},
"Products": {
"Categories": {
"carpet cleaning": {
"OrderItems": [
{
"OrderItemID": "9d398f84-892c-11e3-8f31-18037335d26a",
"Name": "PLB-Leave Behind Item"
}
]
}
}
}
}
}
};
var viewModel = ko.mapping.fromJS(order);
ko.applyBindings(viewModel);
here's a fiddle with the above code: http://jsfiddle.net/mattlokk/6Q5f7/5/
To bind against your structure, you would need to turn the objects into arrays. Given that you are using the mapping plugin, the easiest way would likely be to use a binding that translates an object with properties to an array of key/values.
Here is a sample binding:
ko.bindingHandlers.objectForEach = {
init: function(element, valueAccessor, allBindings, data, context) {
var mapped = ko.computed({
read: function() {
var object = ko.unwrap(valueAccessor()),
result = [];
ko.utils.objectForEach(object, function(key, value) {
var item = {
key: key,
value: value
};
result.push(item);
});
return result;
},
disposeWhenNodeIsRemoved: element
});
//apply the foreach bindings with the mapped values
ko.applyBindingsToNode(element, { foreach: mapped }, context);
return { controlsDescendantBindings: true };
}
};
This will create a computed on-the-fly that maps the object to an array of key/values. Now you can use objectForEach instead of foreach against your objects.
Here is a basic sample: http://jsfiddle.net/rniemeyer/nn3jg/ and here is an example with your fiddle: http://jsfiddle.net/rniemeyer/47Wbe/
Here is the full code.
HTML part:
<script id="company_template" type="text/x-handlebars-template">
{{#each CDataMap}}
<div>{{this}}</div>
{{/each}}
<p></p>
</script>
JS part
var source = $("#company_template").html();
var template = Handlebars.compile(source);
var data= {
"CDataMap" : {
"name": "Jim Cowart",
"location": {
"city": {
"name": "Chattanooga",
"population": 167674
},
"state": {
"name": "Tennessee",
"abbreviation": "TN",
"population": 6403000
}
},
"company": "appendTo"
}
};
$("p").append(template(data));
I want to use this using handlebars js.
When am using it am getting object object display only.
I need the correct code.
The problem with your example is that CDataMap is not an array of objects, so you cannot iterate through them.
This is a valid example:
<script>
(function ($) {
$(function () {
var source = $("#company_template").html();
var template = Handlebars.compile(source);
var data = {
"CDataMap": [{
"name": "Jim Cowart",
"location": {
"city": {
"name": "Chattanooga",
"population": 167674
},
"state": {
"name": "Tennessee",
"abbreviation": "TN",
"population": 6403000
}
},
"company": "appendTo"
}]
};
$("p").append(template(data));
});
})(jQuery);
</script>
And also the p tag or any element you'll use to put the result in must be outside of the template, like this:
<script id="company_template" type="text/x-handlebars-template">
{{#each CDataMap}}
<div>{{this.name}}</div>
<div>{{this.location.city.name}}</div>
{{/each}}
</script>
<p></p>
Handlebar each expects iterative elements. Data which you are supplying needs to be modified.
Below code works
<script id="company_template" type="text/x-handlebarstemplate">
{{#each CDataMap}}
<div>Name : {{this.name}} <br/>
Location: {{this.location.city.name}} <br />
Population: {{this.location.city.population}}
</div>
{{/each}}
</script>
<p></p>
JS side
var data= {
"CDataMap" : [
{
"name": "Jim Cowart",
"location": {
"city": {
"name": "New york",
"population": 494949494
}
}
},
]
};
var templateSource = $("#company_template").html();
template = Handlebars.compile(templateSource);
studentHTML = template(data);
$("p").append(studentHTML);