JavaScript: How to get specific value from JSON data - javascript

I have the following code in which I fetch data from the JSON file , I Store data in $scope.users variable, But I want to fetch only username value how can I do this?
LoginCtrl.js
'use strict';
angular.module('User').controller('LoginCtrl', ['$scope','$state', "SettingService","UserService", function($scope,$state, SettingService,UserService) {
$scope.users = [];
UserService.getLoginInfo().then(function(response){
$scope.users = response.data.data["username"];
}, function(error){
})
var vm = this;
vm.doLogin = function(){
var username = document.forms["loginForm"]["email"].value;
var password = document.forms["loginForm"]["password"].value;
if(username == "admin#gmail.com" )
{
if(password == "admin")
{
$state.go('app.home');
}
}
};
}]);
User.json
{
"result": "success",
"data": [
{ "id": 1, "username":"admin#gmail.com", "password":"admin"}
]
}

you can get value for that JSON value as
response.data.data[0]["username"]
If you want to get all the usernames from the array, then you can do something like this:
var arr = response.data.map(function(a, b){
return a.username;
});
arr will contain all the username details

Related

javascript web data connector doesn't work with optional url parameters

I am trying to use javascript URLSearchParameters in which a user can type in certain fields to get particular data sets in json file.
The URLSearchParameter seems to work for when you select certain fields but it does not seem to parse the URL correctly in certain situations.
For Example symbol and apikey is a required field.
Optional fields are start date and end date.
When I type in symbol and apikey and leave all of the optional fields empty, the script breaks. When I type any one of the optional fields, it works. My code is provided below. My schema is not like this but below is an example that is similar. I have more optional fields in my final code but if all of them are empty my code continues to break.
Also I would like to know if there is any simpler way to write this code as I'm repeating the code in if else statements and I am repeating the code the same way.
(function() {
// Create the connector object
var myConnector = tableau.makeConnector();
// Define the schema
myConnector.getSchema = function(schemaCallback) {
var cols = [{
id: "symbol",
alias: "symbol",
dataType: tableau.dataTypeEnum.string
}, {
id: "date",
alias: "date",
dataType: tableau.dataTypeEnum.date
}
];
var tableSchema = {
id: "My data",
alias:"My daily data ",
columns: cols
};
schemaCallback([tableSchema]);
};
// Download the data
myConnector.getData = function(table, doneCallback) {
var dataObj = JSON.parse(tableau.connectionData);
const searchParams = new URLSearchParams (dataObj);
const apiCall = `https://mywebsite/getMyData.json?${searchParams}`;
$.getJSON(apiCall, function(resp) {
var feat = resp.results,
tableData = [];
// Iterate over the JSON object
for (var i = 0, len = feat.length; i < len; i++) {
tableData.push({
"symbol": feat[i].symbol,
"date": feat[i].date,
});
}
table.appendRows(tableData);
doneCallback();
});
};
tableau.registerConnector(myConnector);
// Create event listeners for when the user submits the form
$(document).ready(function() {
$("#submitButton").click(function()
{
if ($('#symbol').val().trim().length == 0 || $('#apikey').val().trim().length == 0)
{
$('#errorMsg').show().html("Symbol and APi key can't be blank.");
}
else if ($('#start-date').val().trim().length == 0){
var dataObj = {
apikey: $('#apikey').val().trim(),
symbol: $('#symbol').val().trim(),
endDate: $('#end-date').val().trim(),
}
tableau.connectionData = JSON.stringify(dataObj);
tableau.connectionName = "My Data";
tableau.submit();
}
else if ($('#end-date').val().trim().length == 0){
var dataObj = {
apikey: $('#apikey').val().trim(),
symbol: $('#symbol').val().trim(),
startDate: $('#start-date').val().trim(),
}
tableau.connectionData = JSON.stringify(dataObj);
tableau.connectionName = "My Data";
tableau.submit();
}
else if ($('#start-date').val().trim().length == 0 && $('#end-date').val().trim().length == 0){
var dataObj = {
apikey: $('#apikey').val().trim(),
symbol: $('#symbol').val().trim(),
type: $('#type').val().trim(),
}
tableau.connectionData = JSON.stringify(dataObj);
tableau.connectionName = "My Data";
tableau.submit();
}
else{
var dataObj = {
apikey: $('#apikey').val().trim(),
symbol: $('#symbol').val().trim(),
startDate: $('#start-date').val().trim(),
endDate: $('#end-date').val().trim(),
};
tableau.connectionData = JSON.stringify(dataObj);
tableau.connectionName = "My Data";
tableau.submit();
}
});
});
})();

how to remove JSON header from the object array

I have data in this format. This is gamesparks data that is BaaS using for game development.
I am sending this data to the IOS person but he said he can not fetch this type of data so he told me to change the data
This is my actual data
{
"Details": [{
"5d4c2c28dcf224127a30457b": {
"displayName": "ewqeqw"
},
"5d4c4699dcf224127a3045e0": {
"displayName": "mmmmmmmmmm"
}
}]
}
and I need to change data in this format
{
"Details": [{
"ID": "5d499b0fdcf224127a303d61",
"displayName": "qweqewq"
},
{
"ID": "5d499b0fdcf224127a303d61",
"displayName": "qweqewq"
}
]
}
This is my code:
var group = Spark.getData().group;
var API = Spark.getGameDataService();
var all1 = new Array();
var entry = API.getItem("playerFriends", Spark.getPlayer().getPlayerId());
var friendsList = {};
if (entry.error()) {
Spark.setScriptError("ERROR", error);
Spark.exit();
} else {
var data = entry.document().getData();
if (group === "all") {
for (var friendOBJ in data) {
//Set details of player ID and display name in new friendsList
object
friendsList[friendOBJ] = {};
friendsList[friendOBJ].displayName = data[friendOBJ].displayName;
friendsList[friendOBJ].playerId = data[friendOBJ].playerId;
}
all1.push(friendsList);
} else {
for (var friendOBJ in data) {
if (data[friendOBJ].group === group && data[friendOBJ].status ===
"accepted") {
friendsList[friendOBJ] = {};
friendsList[friendOBJ].displayName = data[friendOBJ].displayName;
}
}
}
Spark.setScriptData("Details", all1);
Can you not just make a function to convert the data into the desired shape? Something like this should work:
function formatData(details) {
var formattedDetails = [];
for (var id in details) {
formattedDetails.push({
ID: id,
displayName: details[id].displayName
});
}
return formattedDetails;
}
var data = {
"Details": [
{
"5d4c2c28dcf224127a30457b": {
"displayName": "ewqeqw"
},
"5d4c4699dcf224127a3045e0": {
"displayName": "mmmmmmmmmm"
}
}
]
};
var formattedData = formatData(data.Details[0])
this is the output you want
{
"Details": [{
"ID": "5d499b0fdcf224127a303d61",
"displayName": "qweqewq"
}
}
and this is my code i am explaining each line with comment
var count = 0;
var tmp = { AcceptedFriendList: []}; //make object and inside empty array
for (var friendOBJ in data) { // retrieving data
if(data[friendOBJ].status === "accepted"){ // your condition
var tempObj = {"displayName" :"","playerid": ""}; //this is format you want
tempObj.displayName = data[friendOBJ].displayName; // putting data in spicify format object
tempObj.playerid = data[friendOBJ].ID;
tmp.AcceptedFriendList[count] = tempObj; //assign object back to array
count++; // iterate it so the next data come further.
}}

How to delete data by it's id using AngularJs?

I'm trying to delete data by it's id, but it's not working.
When I set the id of the data i want to delete, it works. I need your help.
My HTML code:
<div data-ng-controller="deletePinCtrl">
<button data-ng-click="deletePin()">delete</button>
</div>
<h3>{{pin.title}}</h3>
<h4>{{pin.content}}</h4>
My Angular code:
.controller("deletePinCtrl", function($scope, $http){
$scope.deletePin = function() {
var obj = { "id": "value"};
var config = { data: JSON.stringify(obj) };
$http.delete('http://localhost:8080/SpringMVCHibernate/rest/delete', config).
then(function(response) {
alert("pin is deleted");
}, function(response) {
alert("try again");
});
}
})
pass you id in function
<button data-ng-click="deletePin(pin.id)">delete</button>
and set here
$scope.deletePin = function(value) {
var obj = { "id": value}; // now id have its id

Reading the JSON values using Javascript/Angular

Hi i am getting the following response from server
{
"Application1": {
"status": "SUCCESS",
"comment": "A123456 added successfully to Application"
},
"Application2": {
"status": "SUCCESS",
"comment": "B67890 added successfully to Application"
}
}
i need to show a message based on the status , we are using angular and javascript i am unable to loop through and read the same, any help would be appreciated
The simpliest version i can imagine:
<script>
var json = {"Application1":{"status":"SUCCESS","comment":"A123456 added successfully to Application"},"Application2":{"status":"SUCCESS","comment":"B67890 added successfully to Application"}};
for(var t in json)
console.log(json[t]['status']);
</script>
You can read the values by parsing the string as json:
var obj = JSON.parse('{"Application1":{"status":"SUCCESS","comment":"A123456 added successfully to Application"},"Application2":{"status":"SUCCESS","comment":"B67890 added successfully to Application"}}')
Then you can get access the values as properties:
obj.Application1.status
First check the response is JSON object or string. If it is string, parse it to JSON. Then you can loop through it.
Use the following functions
isJson(your_response);
will return the JSON object or null.
var whatIsIt = function (object) {
var stringConstructor = "test".constructor;
var arrayConstructor = [].constructor;
var objectConstructor = {}.constructor;
if (object === null) {
return "null";
}
else if (object === undefined) {
return "undefined";
}
else if (object.constructor === stringConstructor) {
return "String";
}
else if (object.constructor === arrayConstructor) {
return "Array";
}
else if (object.constructor === objectConstructor) {
return "Object";
}
else {
return "don't know";
}
};
var isJson = function(o1)
{
// Validate JSON strings
var json_object = null;
var type = whatIsIt(o1);
switch(type)
{
case "String":
try{
json_object = JSON.parse(o1);
}catch (e){
return null;
}
break;
case "Object":
try {
JSON.stringify(o1);
json_object = o1;
}catch (e) {
return null;
}
break;
}
return json_object;
};
Assuming that the communication with the server is carried out in a separate angular service, you need to use ng-repeat and ng-if directives,
Please find the JSFiddle here :
http://jsfiddle.net/2ju3c6tc/1/
var module = angular.module("myModule", []);
module.service('serverCommunicator', ['$http',
function($http) {
//code to get the data from the server
//server Data would hold the JSON object after the AJAX req,however, it is assigned manually over here
this.serverData = {
"Application1": {
"status": "SUCCESS",
"comment": "A123456 added successfully to Application"
},
"Application2": {
"status": "SUCCESS",
"comment": "B67890 added successfully to Application"
}
};
}
]);
module.controller('myController', ['$scope', 'serverCommunicator',
function($scope, serverCommunicator) {
$scope.serverData = serverCommunicator.serverData;
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="myModule">
<div ng-controller="myController as myCont">
<div ng-repeat="dataElement in serverData">
<div ng-if="dataElement.status=='SUCCESS'">
This is success message :{{dataElement.comment}}
</div>
<div ng-if="dataElement.status=='FAILURE'">
This is failure message {{dataElement.comment}}
</div>
</div>
</div>
</div>

AngularJS set var: http get

I have an angular filter set up which works great:
categorieFilter = angular.module("categorieFilter", [])
categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){
$scope.search = "";
$scope.products = [];
$scope.categories = [];
$scope.categories = store.getCategories();
$scope.products = store.getProducts();
$scope.filterProductsByCats = function(category){
$scope.search = category;
};
}])
categorieFilter.factory('store', function(){
var categories = ['Lattes','CC Blend','Frappes'];
var products = [
{name: 'Latte machiatto',category: 'Lattes'},
{name: 'Frappe ice',category: 'Frappes'},
{name: 'Latte caramel',category: 'Lattes'},
{name: 'Frappe speculoos',category: 'Frappes'},
{name: 'Cappucino',category: 'CC Blend'},
{name: 'Filter coffee',category: 'CC Blend'},
];
return {
getCategories : function(){
return categories;
},
getProducts : function(){
return products;
}
};
});
But the var categories and var products are still hard coded so I want to retreive the needed data from my server to fill these variables. And I can't seem to get this right? I have another function where I can get the required data but I don't know how I can get these 2 in 1...?
categories = angular.module('categories', []);
categories.controller("category",function($scope, $http){
var serviceBase = 'api/';
$http.get(serviceBase + 'categories').then(function (results) {
$scope.categories = results.data;
for(var i = 0; i < $scope.categories.length; i++){
var categories = $scope.categories[i];
}
});
});
So how can I properly set the var categories to the required $http.get to retreive my server data into the filter above?
I think you should be able to get rid of the hard coded block in the service and just return:
return {
getCategories: $http.get('/categories').success(function (data) {
return data;
}),
getProducts: $http.get('/products').success(function (data) {
return data;
})
}
Make sure you dependencies are setup correctly for the service though (i.e. $http):
.factory('store', function ($http) {
// The above return block here
});
And this should do the trick!

Categories