calling a json array in angularjs - javascript

I have an json array of
[{
"id": "21390238becde1290",
"chelsea": {
"homeTeam": "chelsea",
"sortName": "ches",
"awayTeam": "Maribor",
"awayShort": ""
},
"barclays": {
"id": "21390238becde1290",
"homeTeam": "barclays",
"sortName": "barc",
"awayTeam": "Hull",
"awayShort": ""
}
}]
Controller:
footBallApp.controller('TeamInfoEdit',
function ($rootScope, $scope, $state, $translate, carwashService) {
$rootScope.washTypes;
$scope.onViewLoaded = function () {
matchService.getTeamTypes($scope.TypeSelected);
}
$scope.TypeSelected = function (response) {
debugger;
if (response) {
$rootScope.teamAvailable = response;
$scope.localizedTeamName = getLocalizedCollection($scope.teamAvailable);
}
}
// Editing the Team Details.
$scope.editTeamDetails = function (key) {
console.log(key._id);
$rootScope.selectTeam =[];
for(var i=0; i<$scope.teamAvailable.length;i++){
if($scope.teamAvailable[i]._id== key._id)
{
console.log($scope.teamAvailable[i]);
$scope.selectTeam.push($scope.teamAvailable[i]);
debugger;
And I have assigned the array to $scope.selectTeam. When Im trying to call $scope.selectTeam.chelsea.Im getting it as Undefined in the console. While calling the json I'm going wrong but couldn't find it, so how do I call the array correctly. So looking for help in this.

I don't know how your array looks like, but try to call:
$scope.selectTeam[0].chelsea

Array is coming because of uninitialized.
If you initialize $rootScope.teamAvailable = {}; then if response data comes in json format it will overwrite.

Related

Print data onto html from within json using 'for' loop based on 'if' condition

I have a json file:
"courses":[{
"code":"101000",
"name":"Bachelor of Education (Primary)"
}, {
"code":"101001",
"name":"Bachelor of Education (Secondary)"
}]
I have managed to get the json data into the page via
$.getJSON('unminified.json', function (data) {
courses = data["courses"];
});
and can access data via chrome console like this
courses[0].name
which returns "Bachelor of Education (Primary)" which is fine.
MY PROBLEM
Is that I want to access name properties based on what the code property is. I've tried below but I keep getting undefined (in chrome console):
function myFunction() {
for(var i = 0; i < courses.length; i++)
{
if(courses[i].code == '101000')
{
return courses[i].name;
};
}
};
Your json is not valid. You need curly braces enclosing the whole thing, and you need commas after the "code" properties:
{
"courses":[
{
"code":"101000",
"name":"Bachelor of Education (Primary)"
},
{
"code":"101001",
"name":"Bachelor of Education (Secondary)"
}
]
}
With corrected json data, myFunction appears to work as expected. I've updated it to take a courses argument instead of referencing a global or parent scope variable.
// mock $.getJSON
const fakeRequest = (callback) => {
const data = {
"courses": [{
"code": "101000",
"name": "Bachelor of Education (Primary)"
}, {
"code": "101001",
"name": "Bachelor of Education (Secondary)"
}]
}
setTimeout(() => callback(data), 200);
}
// invoke the request and handle the response
fakeRequest((response) => {
const {courses} = response;
// pass courses to myFunction, because it
// doesn't exist outside this function scope
const c = myFunction(courses);
// insert into the document
document.querySelector('.name').innerHTML = c;
})
// takes a courses argument to eliminate the
// bad practice of referencing an external variable
function myFunction(courses) {
for (var i = 0; i < courses.length; i++) {
if (courses[i].code == '101000') {
return courses[i].name;
};
}
};
<div class="name"></div>

How to assign JSON data from http.get(//json from server) to Javascript variable?

I have tried everything to assign my JSON data (JSON Object?) with $http.get("https://server url to my json data").success(function (response) {}
to a local variable in javascript, but it doesnt't work. I am really confused with all of this json strings and objects. Here's my code.
Form of my json data which I get from the server
{
"status":"success",
"data":{
"user":{
"username":"user1",
"fullName":"name "
},
"vehicles":[ ],
"chargeBoxes":
[
{
"id":1,
"name":"Station 1",
"availability":"offline",
},
{
"id":2,
"name":"Station 2",
"availability":"online",
},
{
"id":3,
"name":"Station 3",
"availability":"online",
}
]
}
So, my question is how I can use this data an store it in an js array. I need it for my javascript highchart controller. I tried this..
controller.js
myApp = angular.module('ServiceDashboard');
myApp.controller('DataController' function($scope, $http, $interval) {
$http.get("https://server-url.com/../login?username=..&password=..").success(function(response) {
$scope.jsonData = response.data;
});
var categorieData = [];
var json = JSON.parse(jsonData);
for (var i = 0; i <= jsonData.chargeBoxes.length - 1; i++)
{
categorieData[i] = jsonData.chargeBoxes[i].name;
}
//This works really fine when I do it this way (test case) (json variable in just one line and with ' '
// Here I have a json string (one line with ' ')
var jsonData= '{"status": "success", "data": {"chargeboxes":[{..},{..},{..}]}';
// and then I parse this json string to an json object and iterate over it and store the chargeBoxes.name values into the categorieDate array.
But when I try it with the real form of my json data (multiline with {}), then it doesn't work.
var jsonData = {
"status":"success",
"data":{
"user":{
"username":"user1",
"fullName":"name "
},
"vehicles":[ ],
"chargeBoxes":
[
{
"id":1,
"name":"Station 1",
"availability":"offline",
},
{
"id":2,
"name":"Station 2",
"availability":"online",
},
{
"id":3,
"name":"Station 3",
"availability":"online",
}
]
};
I really don't know what to do anymore. First of all, I would like to try it with a local variable like above (var jsonData = {..}; because with oneline string ' ' it works), and then I would like to use this json data directly from the server ($scope.jsondata...).
Thanks!
$http.get is called async.
myApp = angular.module('ServiceDashboard');
myApp.controller('DataController' function($scope, $http, $interval) {
$http.get("https://server-url.com/../login?username=..&password=..").success(function(response) {
$scope.jsonData = response.data;
// >> Put your parse code here
var categorieData = [];
var json = JSON.parse(jsonData);
for (var i = 0; i <= jsonData.chargeBoxes.length - 1; i++)
{
categorieData[i] = jsonData.chargeBoxes[i].name;
}
});
You have multiple issues in your code. First of all the servers response data is not in
$scope.jsonData = response.data;
but you will find it in
$scope.jsonData = response.data.data;
The $http.get returns a json object of the response sent from the server. The response body however is in the data property of the response object being returned. Since the server's response also has a data property you will need to go one level deeper.
Secondly var json = JSON.parse(jsonData); will not work. At the time this line of code is executed the data is not available. Put this in the success callback of your $http.get() method and you'll be fine.
It should look something like this:
myApp = angular.module('ServiceDashboard');
myApp.controller('DataController' function($scope, $http, $interval) {
$http.get("https://server-url.com/../login?username=..&password=..").success(function(response) {
$scope.jsonData = response.data.data;
for (var i in $scope.jsonData.chargeBoxes)
categorieData.push(jsonData.chargeBoxes[i].name);
});
You need to process your jsonData in the success-method of the $http.get() call, since it's asynchronous.
controller.js
var myApp = angular.module('ServiceDashboard');
myApp.controller('DataController' function($scope, $http, $interval) {
$scope.barChartConfig = { categories: [] };
$http.get("https://server-url.com/../login?username=..&password=..").success(function(response) {
$scope.jsonData = response.data.data;
var json = JSON.parse($scope.jsonData);
var categorieData = [];
for (var i = 0; i <= json.chargeBoxes.length - 1; i++)
{
categorieData.push($scope.jsonData.chargeBoxes[i].name);
}
$scope.barChartConfig.categories = categorieData;
});
var url = "http://<domainname>/<url>"
var jsonData = $.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Check your json response in jsonData variable.

Return object from multiple getJSON responses

I have a function that calls a paginated API, loops through each of the pages and returns data from from each of the responses:
function nextPage(url) {
if (!url) {
return;
}
$.getJSON(url, function(data) {
nextPage(data.next);
$.each(data.results, function (k, v) {
console.log(v.city_name);
});
});
}
nextPage('http://url.com/api/v1/cities/?page=1');
Currently, when I log the response to the console I get something that looks like this:
Paris
Brussels
Mexico City
...
But what I want is a structure that looks this this:
[
{item: 'Paris'},
{item: 'Brussels'},
{item: 'Mexico City'}
]
For reference the response data looks like this:
{
"count": 105,
"next": "http://url.com/api/v1/cities/?page=2",
"previous": null,
"results": [
{
"city_detail": "http://url.com/api/v1/cities/1/",
"city_name": "Paris"
},
{
"city_detail": "http://url.com/api/v1/cities/2/",
"city_name": "Brussels"
},
{
"city_detail": "http://url.com/api/v1/cities/3/",
"city_name": "Mexico City"
}
]
}
I know the answer is staring me in the face and is probably v. simple, but my lack of javascript knowledge is letting me down. Would appreciate help solving this. Thanks!
EDIT
The problem seems to be that the nextPage function makes multiple calls, returning data from each page of JSON. I can get this data into multiple objects, but not one object representing all the responses.
So basically you want to store key:value pair to an object..:
Dot Notation:
var cities = {}
function nextPage(url) {
if (!url) {
return;
}
$.getJSON(url, function(data) {
nextPage(data.next);
$.each(data.results, function (k, v) {
console.log(v.city_name);
cities.name = v.city_name //Push to an object
});
});
}
So youll get this as a response:
cities = [
{city: 'Paris'},
{city: 'Brussels'},
{city: 'Mexico City'}
]
Bracket Notation:
var cities = {}
function nextPage(url) {
if (!url) {
return;
}
$.getJSON(url, function(data) {
nextPage(data.next);
$.each(data.results, function (k, v) {
console.log(v.city_name);
cities["name"]= v.city_name //Push to an object
});
});
}
Result
:
(Same for both)
cities = [
{city: 'Paris'},
{city: 'Brussels'},
{city: 'Mexico City'}
]
EDIT
Ok so there was another problem! It was sneaky but we finnaly caught it. So the problem was here:
$.getJSON(url, function(data) {
console.log(data.results)
nextPage(data.next);
$.each(data, function (k, v) {
cities["title"]= v.title //Push to an object
});
});
There now, you see it says data.results ... Actually data.results is an empty undefined variable.. What you should do is only data which consists the whole data. You might not understand it now but look over the code i represented below ...
var dataJSON;
function nextPage(url) {
if (!url) {
return;
}
$.getJSON(url, function(data) {
console.log(data) //This consits the data on the below provided url...
dataJSON = data; // Just making a public variable assigned to the data..
nextPage(data.next);
$.each(data, function (k, v) {
});
});
}
nextPage('https://cdn.rawgit.com/amanuel2/Collabs/master/list.json')
Plunker go to console to view data....
EDIT2
Ok this is preety much your JSON File i put in GITHUB, so i have a secure HTTPS://.. Anways here i just did data.results and i got this result:
And here is the Plunker! Hope this helped!!
EDIT3
Ok now this is the last bit.. With your 2nd JSON Page.. You 2nd JSON Page had actually syntax errors.. So i fixed those put it in github and uploaded the new JSON.. Here is the plunker..
Link to Read More about Objects..
var results = []
function nextPage(url) {
if (!url) {
return;
}
$.getJSON(url, function(data) {
nextPage(data.next);
$.each(data.results, function (k, v) {
results.push({item: v.city_name})
console.log(v.city_name);
});
});
}
console.log(results)
// should show an array with {item: city_name} objects.
this allows the results array to be accessed in the outer scoped as well.

How to synchronize the function commands in angular js

I am creating an ionic application and in particular scenario
when an employee is selected from a list(generated from a JSON data array), his detail is to be shown from here
var employees = [{"id": 325, "firstName": "James", "lastName":
"King", "managerId": 0, "managerName": "", "reports": 4, "title":
"President and CEO", "department": "Corporate", "cellPhone":
"617-000-0001", "officePhone": "781-000-0001", "email":
"jking#gmail.com", "city": "Boston, MA", "pic": "James_King.jpg",
"twitterId": "#fakejking", "blog": "http://coenraets.org"}.....
All i need is to find the index of ID to show the complete object.
findById: function(employeeId) {
var deferred = $q.defer();
var searchValue = {'id': employeeId };
index = -1;
_.each(employees, function(data, idx) {
if (_.isEqual(data, searchValue)) {
index = idx;
return;
}
});
var employee = employees[index];
deferred.resolve(employee);
return deferred.promise;
},
for that i am using this function which is not taking debugger inside the _.each function
kindly tell me where m i wrong.
It's not going to work because expression _.isEqual(employees[xxx], {id: 325}) will never return a match.
Instead use _.find method
findById: function(employeeId) {
var employee = _.find(employees, {id: employeeId});
return $q.when(employee);
}
I think you can simplify your function a little, because you are using lodash:
findById: funtion(employeeId) {
return _.findWhere(employees, {id : employeeId});
}
Futhermore I do not see any reason to use promises here, but to go with that notion, you could try this:
findById: funtion(employeeId) {
var deferred = $q.defer();
$timeout(function() {
var employee = _.findWhere(employees, {id : employeeId});
if (found !== undefined) {
deferred.resolve(employee);
} else {
deferred.reject();
}, 0);
return deferred.promise;
}
You need to return the promise deferred.promise before you resolve() or reject(), so you can wait for that in your callee.
Hope that helps!
I don't know if your really need the index. To work on a solution, which returns the employee at that moment, when you find the data, would be better and shorter. Than you should also jump out of the loop.
If your debugger is not jumping inside _.each maybe your employees array is empty.
You could try something like this:
findById: function(employeeId) {
var deferred = $q.defer();
// deferred should be inside the scope of _.each
// because it is defined here
var searchValue = {'id': employeeId };
//index = -1;
// check your data here
// for example console.log(employees.length)
// or make a breakpoint here and check employees
_.each(employees, function(data, idx) {
// make a console.log(idx) here to check your data
if (_.isEqual(data, searchValue)) {
deferred.resolve(data);
return deferred.promise;;
}
});
},

IndexedDB and Javascript: JSON and objects misunderstanding

I'm trying to obtain information from a JSON file download to the client through AJAX and I'm getting different results depending on the JSON format and I don't know how to fix the one with problem.
First case:
The json files looks like:
[{"name": "nick",
"age": 28},
{"name": "katie",
"age": 32}]
My AJAX .done method looks like:
.done(
function(data) {
addObjectsDB (data, "people");
})
This method calls a second one that iterates through data and stored correctly each object into IndexedDB.
Second case:
Now I have a JSON file with different format:
[
{
"husband": {
"name": "Jhon",
"age": 23 },
"wife": {
"name": "Marie",
"age": 24 }
}
]
Now my .done() AJAX method iterates through data and add each person, husband or wife to an array which is then sent to the DB with the same method than the first case:
.done(
function(data) {
var people = [];
$(data).each(function (key, value){
people.push(value.husband);
people.push(value.wife);
});
addObjectsDB (people, "people");
})
In this case the insertion into the database fails, if for example, instead of adding value.husband to people array I just add value to people array the insertion works, but I need each person stored separated in the DB.
The addObjectsDB method is:
function addObjectsDB (data, collection) {
var objectStore = db.transaction(collection, "readwrite").objectStore(collection);
$.each (data, function (key, value) {
var request = objectStore.add(value);
});
}
As I said the first case works perfectly but the second one inserts nothing and no error is showed...
I think the problem is that I don't understand javascript types adequately but I'm starting with it and I've spent a whole evening with it.
There's nothing wrong with your IDB code. Look for your answer in the code you haven't presented, particularily the AJAX response (is your JSON parsed the way you think it is?)
Be sure to attach event listeners for the error event. I'm positive that if your IDB "inserts nothing" then in fact it's not true that "no error is showed" and rather no error is seen due to callback mismanagement.
Here's a working implementation, modified from a previous answer I've given on this tag. This implementation doesn't have the uniqueness constraints you've put on your schema on purpose: it shows that your looping is fine. The entries below all look good.
var db_name = 'SO_22977915',
store_name = 'people';
$.ajax({
url: '/echo/json/',
type: 'post',
dataType: 'json',
data: {
json: JSON.stringify({
case1: [{
"name": "nick",
"age": 28
}, {
"name": "katie",
"age": 32
}],
case2: [{
"husband": {
"name": "Jhon",
"age": 23
},
"wife": {
"name": "Marie",
"age": 24
}
}]
})
},
success: function (data) {
var request,
upgrade = false,
doTx = function (db, entry) {
addData(db, entry, function () {
getData(db);
});
},
getData = function (db) {
db.transaction([store_name], "readonly").objectStore(store_name).openCursor(IDBKeyRange.lowerBound(0)).onsuccess = function (event) {
var cursor = event.target.result;
if (null !== cursor) {
console.log("entry", cursor.value);
cursor.continue();
}
};
},
addData = function (db, entry, finished) {
console.log('adding', entry);
var tx = db.transaction([store_name], "readwrite"),
people = [];
tx.addEventListener('complete', function (e) {
finished();
});
$.each(entry.case1, function (key, value) {
tx.objectStore(store_name).add(value);
});
$(entry.case2).each(function (key, value){
people.push(value.husband);
people.push(value.wife);
});
$.each(people, function (key, value) {
tx.objectStore(store_name).add(value);
});
};
request = window.indexedDB.open(db_name);
request.oncomplete = function (event) {
if (upgrade) {
doTx(request.result, data);
}
};
request.onsuccess = function (event) {
if (!upgrade) {
doTx(request.result, data);
}
};
request.onupgradeneeded = function (event) {
var db = event.target.result;
db.createObjectStore(store_name, {
keyPath: null,
autoIncrement: true
});
}
}
});
A cursor and console.log shows all entries as being added:

Categories

Resources