How can we remove square brackets [] and double quotes "" in angular js? - html

I am using MEAN stack in my application with AngularJS as my front-end. How can I remove Square Brackets [] and Double quotes "" in repeated answer, My plunker actually we need show role vlaues in my app so we have used ng-repeat="mani in name.comments " to get the answer, and we got the answer like ["user"], ["admin"], ["kp"] , what we exactly looking we just need to show the values alone, not with the [] Square Brackets and Double quotes.... for example answer would be:- values are without in [] Square Brackets and Double quotes like 1. user , 2. admin, 3. kp
My Data:-
$scope.name = {
"_id": "5863d3aaacaeddc00663bc07",
"comments": [
{
"created": 1485511936350,
"role": [
"user"
],
"email": "selvam#e21designs.com",
"name": "selvam R",
"commentText": "mani selvam"
},
{
"created": 1485511936350,
"role": [
"admin"
],
"email": "selvam#e21designs.com",
"name": "selvam R",
"commentText": "mani selvam"
},
{
"created": 1485511936350,
"role": [
"kp"
],
"email": "selvam#e21designs.com",
"name": "selvam R",
"commentText": "mani selvam"
}
],
"created": "2016-12-28T15:00:58.777Z",
"isCurrentUserOwner": false
};
My Html:-
<div ng-repeat="mani in name.comments ">
<td>{{$index + 1}}</td>
<td>{{mani.role }}</td>
</div>
Please look at into My plunker for reference ...
Expecting answer would be without [] Square Brackets and Double quotes...
This role are within the array so that only it's showing with [] Square Brackets and Double quotes , so how can we remove this , we need to show only values... we have tried many ways we know it's simple task but we unable to solve this issue..
can we use css to remove this ?... any one knows the solution please help us... thanks
please update plunker as well to know the exact solution....

You can use the toString() method to convert the array that is being displayed to a string. Like so:
<td>{{mani.role.toString()}}</td>
That will display it as a string so the " and [] will be removed.
Plunkr showing this.

You just need to select the first element of the array at index 0 using:
{{ mani.role[0] }}
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = {
"_id": "5863d3aaacaeddc00663bc07",
"comments": [{
"created": 1485511936350,
"role": [
"user"
],
"email": "selvam#e21designs.com",
"name": "selvam R",
"commentText": "mani selvam"
}, {
"created": 1485511936350,
"role": [
"admin"
],
"email": "selvam#e21designs.com",
"name": "selvam R",
"commentText": "mani selvam"
}, {
"created": 1485511936350,
"role": [
"kp"
],
"email": "selvam#e21designs.com",
"name": "selvam R",
"commentText": "mani selvam"
}],
"created": "2016-12-28T15:00:58.777Z",
"isCurrentUserOwner": false
};
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.10/angular.min.js" data-semver="1.5.10"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="mani in name.comments ">
<td>{{$index + 1}}</td>
<td>{{ mani.role[0] }}</td>
</div>
</body>
</html>

Your mani.role is an array, so do something like this:
<td><span ng-repeat="r in mani.role">{{ r }} </span></td>

Your data looks like Json data, so what you need is to read Json data through AngularJS by creating module like this:
var App = angular.module('App', []);
App.controller('Ctrl', function($scope, $http) {
$http.get('data.json')
.then(function(res){
$scope.data = res.data;
});
});
Also, w3schools helpful in your case $http in AngularJS

Related

Convert JSON to nodes and links?

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>

How to add items dynamically to a polymer paper-tree?

I am using polymer paper-tree element in my code.Its displays the tree perfectly with static data,however when I try to add an item dynamically it doesn't work. I am attaching a screenshot here.enter image description here
//Array
this.itemArray = {"name": "Project",
"icon": "theaters",
"open": true,
"children": [{
"name": "Quotes",
"icon": "theaters",
"open": true,
"children": [{
"name": "Breaking Bad",
"icon": "theaters"
}]
}, {
"name": "Templates",
"icon": "theaters",
"open": true,
"children": [{
"name": "Breaking Bad",
"icon": "theaters"
}, {
"name": "Game of Thrones",
"icon": "theaters"
}]
}]
}
//Js code which accepts value from a text box and adds it to the array.
this.$.additem.addEventListener("click", function(){
enter code herevar data = self.$.txtData.value;
self.itemArray.children[1].children.push(
{'name':data,
'icon':'theaters'});
self.addData(self.itemArray,data);
self.$.txtData.value = " ";
});
// addData function
addData:function(itemsarr){
console.log("calling items array function",this.tree);
var tempArr = [];
tempArr = itemsarr;
if(this.tree){
this.$.temp.removeChild(this.tree);
//tempArr = itemsarr; //= this.itemArray2;
}
this.tree = document.createElement('paper-tree-node');
this.tree.setAttribute('id','treemenu');
this.$.temp.appendChild(this.tree);
this.tree.data = tempArr;
console.log(tempArr);
}
Polymer paper-tree have a data property. You just need to update it.
Help link: https://github.com/vpusher/paper-tree/blob/master/paper-tree.html

Query a nested JSON Object/Array with underscore

Assumed that is the JSON structure:
var myData = [
{
"id": 68,
"country": "US",
},
{
"id": 82,
"country": "PL",
},
{
"id": 83,
"country": "US",
}
];
I want to get all items, where country == US
Following try does not work:
var myResult = _.where (myData, {'country': 'US'});
I get an empty result > myResult []
What is the mistake?
EDIT: Sorry, the use of lodash and underscore together was the problem !
I never used underscore.js before, but I have tried your code and it works totally.
Please make sure that you are importing the library.
I have used the next code in the body tag of an empty HTML file:
<script src="http://underscorejs.org/underscore-min.js"></script>
<script>
var myData = [
{
"id": 68,
"country": "US",
},
{
"id": 82,
"country": "PL",
},
{
"id": 83,
"country": "US",
}
];
var myResult = _.where (myData, {'country': 'US'});
console.log(myResult);
</script>
And the result is:

Get "id" value from httpget json response

Below is my JSON output received post the HttpGet successful execution.
{
"results": [{
"id": "1310760",
"type": "page",
"status": "current",
"title": "UniversalProfile Release Test",
"extensions": {
"position": 9
},
"_links": {
"webui": "/display/ds/UniversalProfile+Release+Test",
"tinyui": "/x/KAAU",
"self": "http:1310760"
},
"_expandable": {
"container": "/rest/api/space/ds",
"metadata": "",
"operations": "",
"children": "/rest/api/content/1310760/child",
"history": "/rest/api/content/1310760/history",
"ancestors": "",
"body": "",
"version": "",
"descendants": "/rest/api/content/1310760/descendant",
"space": "/rest/api/space/ds"
}
}],
"start": 0,
"limit": 25,
"size": 1,
"_links": {
"self": "UniversalProfile+Release+Test",
"base": "https://alim4azad.atlassian.net/wiki",
"context": "/wiki"
}
}
I am trying to extract the value for "id" but have been unsuccessful so far.
If your JSON is in the variable output in Javascript, it'd be :
output.results[0]["id"]
Like console.log(output.results[0]["id"]).
Your results section contains arrays. You want the first (0), and then the key id.
Looking at that resulting JSON hurts my brain.
Assuming you are using JavaScript, try this: output.results[0]['id']
Try This:
JSONObject jsonObject = new JSONObject(data);
JSONArray jsonArray = jsonObject.getJSONArray("results");
JSONObject jsonObject1 = jsonArray.getJSONObject(0).getString("id");
Finally i found a solution for it . Below is the solution.
JSONArray results = getbodyPage.getJSONArray("results");
JSONObject first = results.getJSONObject(0);
Long id = first.getLong("id"); // Get id of the found page
System.out.println("INFO : Found ID - " + id);
Thank you all for your valuable inputs.

How to drill down JSON with ng-repeat

I have been stuck on displaying data with ng-repeat. the only thing I have been able to do is display the one of the two objects. Every Customer can have multiple Users. I am trying to display the Users in a table with there CustomerId.
Working plunkr
app.controller('MainCtrl', function ($scope) {
var json = [
{
"CustomerId": "12xsd-344-fv23", "CompanyName": "ConocoPhillips",
"Address": "1234 Main St", "City": "Redmond", "State": "WA", "Zip": "10999",
"Email": "debra#example.com",
"Users": [
{
"FirstName": "Rudy", "LastName": "Sanchez", "CustomerId": "12xsd-344-fv23", "Customer": null,
"Email": "admin#energy.com", "EmailConfirmed": true, "PasswordHash": "AGtuCXr",
"SecurityStamp": "b0fca140", "PhoneNumber": null, "PhoneNumberConfirmed": false, "TwoFactorEnabled": false,
"LockoutEndDateUtc": null, "LockoutEnabled": false, "AccessFailedCount": 0, "Roles": [], "Claims": [], "Logins": [],
"Id": "49b5", "UserName": "admin"
},
{
"FirstName": "Troy", "LastName": "Benbow", "CustomerId": "12xsd-344-fv23", "Customer": null,
"Email": "tbenbow#yahoo.com", "EmailConfirmed": true, "PasswordHash": "AM8wL+iHaSG",
"SecurityStamp": "14f1483a-2e6f-41da-8307-a6c5945984a9", "PhoneNumber": null, "PhoneNumberConfirmed": false, "TwoFactorEnabled": false,
"LockoutEndDateUtc": null, "LockoutEnabled": true, "AccessFailedCount": 0, "Roles": [], "Claims": [], "Logins": [],
"Id": "9985b820-a45", "UserName": "tbenbow"
}
]
},
];
$scope.customers = json;
});
Since, CustomerId is also a property of User, you could make a list of Users in the controller and then loop them in the table:
$scope.users = [];
for(var i = 0; i < $scope.customers.length; i++) {
for(var j = 0; j < $scope.customers[i].Users.length; j++) {
//now you have access to customer properties with $scope.customers[i]
var user = $scope.customers[i].Users[j];
//example of adding CompanyName property
user.CompanyName = $scope.customers[i].CompanyName;
//add user to $scope.users
$scope.users.push(user);
}
}
And then just ng-repeat the users:
<tr ng-repeat="user in users">
<td>{{user.FirstName}} {{user.LastName}}</td>
<td>{{user.UserName}}</td>
<td>{{user.Email}}</td>
<td>{{user.CustomerId}}</td>
<td>{{user.CustomerName}}</td>
</tr>
Here is an updated plunker.
In fact, even if you need a property on the parent Customer part of json, you can add the property to the users array being repeated.
Preparing the data for view will often simplify template tricks (like having to build the table with extra ng-repeated elements. IMO, this is preferable.
There are two possible solutions for this problem, the first one ( rearranging your data in your controller) has already been mentioned in the other answer.
Another way would be a nested loop which I implemented like this:
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css">
<script src="http://code.angularjs.org/1.1.4/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>UserName</th>
<th>Email</th>
<th>CustomerId</th>
</tr>
</thead>
<tbody ng-repeat="customer in customers">
<tr ng-repeat="user in customer.Users">
<td>{{user.FirstName}} {{user.LastName}} {{customer.CustomerId}}</td>
<td>{{user.UserName}}</td>
<td>{{user.Email}}</td>
<td>{{user.CustomerId}}</td>
</tr>
</tbody>
</table>
</body>
</html>
This solution is fast and easy to implement and gives you access to both the user and customer. I would still suggest to rebuild your data in your controller most of the time as it keeps your views clean and keeps any real logic in your controller (Check here for an example of that).
But this example is so simple that you can easily handle it in a nested ng-repeat.