Angularjs - How to call an array inside JSON data to html - javascript

I have a little problem.. I've got this JSON data:
[
{
"students": {
"student_id": "2",
"student_school": "1",
"student_name": "Charles"
},
"parents": [
{
"parent_id": "2",
"parent_school": "1",
"parent_name": "Tim"
}
]
},
{
"students": {
"student_id": "3",
"student_school": "1",
"student_name": "Johnny"
},
"parents": [
{
"parent_id": "3",
"parent_school": "1",
"parent_name": "Kate"
}
]
}
]
The problem is that I try to call to my html page by angular:
{{student.student.student_name}}
Yeah it works but when I want to call the parents data it doesn´t...
{{student.parents.parent_name}}

Simply:
<div ng-repeat="student in data">
{{student.students.student_name}}
{{student.parents[0].parent_name}}
</div>
Or define function in scope called for example getParentDescription and than
<div ng-repeat="student in data">
{{student.students.student_name}}
{{getParentDescription(student)}}
</div>

Because parents is an array. You must specify the index (0 in your case). See the response here : How to get value from a nested JSON array in AngularJS template?

You can't access child scopes directly from parents. See the comment by Vittorio suggesting<ng-repeat="child in parent.children"/> also Binding to Primitives

I'm guessing student is from an ng-repeat where you go through each object in the array.
Take a closer look at your JSON. While "students": {} points to an object, "parents": [] points to an array. Fix your JSON and it'll be fine

Related

check if item exists in json file then get it if exists. And if not complete executing the code

I get a json file from outer link by ajax call. i want to check element is exists in this json file or not and get it if exists. because it changes every time and items increases or decreases. If I get item and this item not existing, I get error and the code not complete. i want to check this item json.children[1].children and json.children[2].children ,..... if exists.
{
"num": 1,
"name": "aa",
"properites": [
{
"name": "prop1",
"value": "value1"
}
],
"children": [
{
"num2": 1,
"name2": "name2",
"properites": [
{
"name": "name",
"value": "value"
}
],
"children": []
},
{
"name": 1,
"num": "1",
"attributes": [
{
"name": "name",
"value": "value"
}
],
"children": []
.......................... big json file
I have tried to get these Items and set in local storage to use in table by this:
localStorage.setItem("row1-item1", json.children[1].children);
localStorage.setItem("row1-item2", json.children[2].children);
localStorage.setItem("row1-item3", json.children[3].children);
localStorage.setItem("row1-item4", json.children[4].children);
localStorage.setItem("row2-item1", json.name[1].children);
localStorage.setItem("row2-item2", json.name[2].children);
localStorage.setItem("row2-item3", json.name[3].children);
localStorage.setItem("row2-item4", json.name[4].children);
the problem here is if json.children[4].children not existing the code not complete the next line and jump out of ajax call even if json.name[1].children is exists. I tried try/catch but not solved it
Try to use map
json.children.map((children,index)=>{
localStorage.setItem('row${index}-item${index}`, children);
}
Or you can use forEach or for loop instead of map.

How to get specific data from object array?

I'm a beginner and would like to know how I can get a specific object from an array
I have an Array that looks like this:
data {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
},
To get the data from above I would do something like this:
return this.data.orderid
But how can I go deeper and get the status in userinfo?
return this.data.orderid.userinfo.status
doesn't work... anyone have any ideas?
A few points:
data is not an array, is an Object (see the curly braces, arrays have squared brackets). To be really precise, your syntax is invalid, but I assume you wanted to type data = { ... }, as opposed to data { ... }
Your syntax is almost correct, the only mistake you are making is that userinfo is an array, and arrays have numeric indexes (I.e. array[0], array[1]). What you are looking for is this.data.orderid.userinfo[0].status
Use data.userinfo[0].status to get the value (in your case this.data.userinfo[0].status)
var data = {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
};
console.log(data.userinfo[0].status);
User Info is an array, so you would need to access it using indexer like so:
return this.data.userinfo[0].status
MDN on arrays: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
You need to iterate over data.userinfo (it's an array)
var data = {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
};
data.userinfo.forEach(function(element) {
console.log(element.status);
});

JSON list optimization

I want to create a JSON API that returns a list of objects. Each object has an id, a name and some other information. API is consumed using JavaScript.
The natural options for my JSON output seems to be:
"myList": [
{
"id": 1,
"name": "object1",
"details": {}
},
{
"id": 2,
"name": "object2",
"details": {}
},
{
"id": 3,
"name": "object3",
"details": {}
},
]
Now let's imagine that I use my API to get all the objects but want to first do something with id2 then something else with id1 and id3.
Then I may be interested to be able to directly get the object for a specific id:
"myList": {
"1": {
"name": "object1",
"details": {}
},
"2": {
"name": "object2",
"details": {}
},
"3": {
"name": "object3",
"details": {}
},
}
This second option may be less natural when somewhere else in the code I want to simply loop through all the elements.
Is there a good practice for these use cases when the API is used for both looping through all elements and sometime using specific elements only (without doing a dedicated call for each element)?
In your example you've changed the ID value from 1 to id1. This would make operating on the data a bit annoying, because you have to add and remove id all the time.
If you didn't do that, and you were relying on the sorted order of the object, you may be in for a surprise, depending on JS engine:
var source = JSON.stringify({z: "first", a: "second", 0: "third"});
var parsed = JSON.parse(source);
console.log(Object.keys(parsed));
// ["0", "z", "a"]
My experience is to work with arrays on the transport layer and index the data (i.e. convert array to map) when required.

How to form mongoose query for $all in array

Given this collection:
[{
"users": [{
"name": "one"
}, {
"name": "two"
}]
}, {
"users": [{
"name": "one"
}, {
"name": "three"
}]
}, {
"users": [{
"name": "fifteen"
}, {
"name": "one"
}]
}]
How can I query this using values (ie, "one" and "two") so that the findOne method returns only the document that has both "name":"one"and "name":"two" (order not relevant)? The users array will always have 2 elements, no more, no less.
I was trying something along the lines of:
Collection.findOne({"users":{$all:["one", "two"]}})
But it isn't working. Can anyone help?
EDIT: Latest attempt:
Collection.findOne({"users":{"name": {$all:["one","two"]}}})
Try this one:
{"users": {$all: [{"name": "one"}, {"name": "two"}]}}
Or use dot notation as proposed by JohnnyHK.
See here how $all is used: https://docs.mongodb.org/manual/reference/operator/query/all/
EDIT: Data was changed.
You can do this by using dot notation to identify a specific field within the array to which the $all operator should be applied:
Collection.findOne({'users.name': {$all: ['one', 'two']}})

Populate AngularJS {{expression}} within ng-repeat using a second array

I'm completely rebuilding my website (originally hacked together with Wordpress) using Laravel and AngularJS. It's been a massive learning experience and I think I'm nearly there but for one problem.
On my site 'schemes' (or courses) are made up of 'units' which are made up of 'lessons'. Retrieving this data is fine, using Eloquent I retrieve valid JSON like this made up example...
[
{
"id": "1", //Scheme Id
"title": "Sports",
"description": "This is a Sports course!",
"units": [
{
"id": "1",
"title": "Tennis",
"lessons": [
{
"id": "6",
"title": "Serving"
},
{
"id": "7",
"title": "Hitting the ball with top-spin"
}
]
},
{
"id": "2",
"title": "Athletics",
"lessons": [
{
"id": "1",
"title": "Long Jump"
},
{
"id": "2",
"title": "Hurdling Technique"
}
]
},
{
"id": "4",
"title": "Golf",
"lessons": [
{
"id": "4",
"title": "Pitching"
},
{
"id": "5",
"title": "Putting"
}
]
}
]
}
....
]
Separately I have a simple array of completed lesson ids for a particular user like this...
[2, 6, 8, 9] ///User has completed lessons with ids of 2,6,8 and 9
In my view I'm using nested ng-repeat loops like so...
...
<div ng-controller="SchemesController">
<div ng-repeat="scheme in schemes">
<h1>{{scheme.title}}</h1>
<div ng-repeat="unit in scheme.units">
<h3>{{unit.title}}</h3>
<div ng-repeat="lesson in unit.lessons">
<div>{{lesson.title}}: {{status}}</div>
</div>
</div>
</div>
</div><!--[end of ng-controller="SchemesController"]-->
....
SchemesController (v simple!) looks like this...
var app = angular.module('schemesApp', []);
app.controller('SchemesController', function($scope){
$scope.schemes=jsonData;
});
The problem is I have no idea how to populate the {{status}} field which I want to state simply 'Complete' or 'Incomplete. I investigated whether I could somehow add this info to my original array like this...
"lessons": [
{
"id": "6",
"title": "Serving",
"status": "Complete" //populated somehow
},
{
"id": "7",
"title": "Hitting the ball with top-spin",
}
]
but I got nowhere slowly. Is there a way to do this (I've played around with underscore.js and felt this could help?).
Or do I populate {{status}} from creating and calling a javascript function?!?
ANY help that anyone could offer would be incredible. I'm a school teacher and for some sadistic reason I find a bit of programming/web design a fun use of my spare time so I apologise if this is a stupid question. THANKS in advance!!!
btw if anyone has a better 'title' for this question then please let me know.
I'm assuming you don't need to persist the status back to the database...
This is where you're having the problem:
<div>{{lesson.title}}: {{status}}</div>
You really don't need to store the status in your data model, because it's just used for presentation purposes.
Let's say your array of completed lessons is defined like this:
$scope.completedLessons = [1, 2, 3, 4, 5] // Or however you'd assign it
You need to create a function in your scope like this:
$scope.isLessonCompleted = function(lessonId) {
return $scope.completedLessons.indexOf(lessonId) > -1;
};
Then you need to change the html from above to this:
<div>{{lesson.title}}: {{isLessonCompleted(lesson.id) && 'Complete' || 'Incomplete'}}</div>
If lessons are also a model and each lesson should have a status, which isn't a column/field in your table but is something you'll add logic to determine, you could add a custom model accessor by adding the following to your models/Lesson.php:
// Append custom accessor attributes
protected $appends = ['status'];
public function getStatusAttribute() {
// Add logic here
return 'Complete';
}
This way, when you use Eloquent to retrieve your data, you'll also see a status attribute as part of the object, so you could then access it as usual $lesson->status (PHP) or lesson.status (JS).
For more information, see the official Laravel documentation on accessors and mutators

Categories

Resources