json arrays of object with quotaions mark - angularjs

I am trying to send an json object to my apiController :
myJson Object that I construct dynamicaly like this :
var course= new Object();
course.info= $scope.info;
course.studentList = [];
course.studentList = $scope.results;
$scope.results is an array that I get from my view :
<select ng-model="results[$index]" >
<option value=""></option>
<option ng-repeat="r in myList" value={{r}}>{{r.studlastname}}</option>
</select>
what I expect :
{
"course": {
"courseName":"yyy",
"courseDesc":"xxxx",
"prof":"prof1"
},
"studentList" :[
{"studfirstname":"2","studlastname":"","studAge":"21"},
{"studfirstname":"4","studlastname":"","studAge":"40"},
{"studfirstname":"6","studlastname":"","studAge":"60"}
]
}
what I have :
{
"course": {
"courseName":"yyy",
"courseDesc":"xxxx",
"prof":"prof1"
},
"studentList" :[
"{"studfirstname":"2","studlastname":"","studAge":"21"}",
"{"studfirstname":"4","studlastname":"","studAge":"40"}",
"{"studfirstname":"6","studlastname":"","studAge":"60"}"
]
}
notice the quotations on every studentList element, this is causing deserialization problem on server side.
please can you help me to remove the quotations ?
thank you in advance.

From what I can see, Problem here is this
course.studentList = $scope.results;
because this line is adding string into your JSON Object as ng-model gives you string instead of object what you are adding in JSON Array.
course.studentList = JSON.parse($scope.results);

I found an easy solution :
let objectArray = $scope.results.map((each)=>{return JSON.parse(each)});
course.studentsList = objectArray;
this solved my problem.

Related

can not map array inside of object

I am lost here, can not find a way how to map through an array that is inside of object. I have received an object from API that includes an array wit values like this:
{
"shelters": [
{
"id": 1,
"name": "Útulok pre psov - TEZAS"
},
{
"id": 2,
"name": "OZ Tuláčik Brezno"
}
]
}
now I need to iterate through the array that is inside and take action on every item to populate the DOM.
my code is:
render() {
// const { isPending, shelters} = this.props;
if (this.props.isPending === false) {
var listOfShelters = this.props.shelters;
console.log('loaded', typeof(listOfShelters), listOfShelters)
return (
<div>
<select style={this.selector} name="útulky" onChange={this.sendId}>
{ listOfShelters.shelters.map(function(shelter, i) {
<option id={shelter.id}>{shelter.name}</option>
})}
</select>
</div>
)
} else if (this.props.isPending === true) {
console.log('fetching')
return (
<select style={this.selector} name="útulky" onChange={this.sendId}>
<option id='0'> Nahravam Data... </option>
</select>
)}
}
I get typeof always an object even if I do this.props.shelters.shelters which should be direct access to that array. if I do this.props.shelters.shelters.map nothing happens, my list of shelters does not get populated. it stays empty. Where do I make the mistake here?
I have found what the problem was. I had different set of parentheses in the .map function, I was using {} instead of (). Now it works like a dream.

How to sort ng-repeat key value pair getting from firebase

i new to angularJS i am getting key value pair from firebase how to sort by timeStamp to show latest at top.
please help me . thanks in advance, orderBy and reverse not working
var ref = new Firebase("https://firebaseio.com/notifications/");
var fb = $firebase(ref);
var syncArreglo = fb.$asObject();
syncArreglo.$loaded().then(function() {
angular.forEach(syncArreglo, function (value, key) {
if(syncArreglo.value != null){
syncArreglo.value.firebaseKey = syncArreglo.key;
}
});
});
syncArreglo.$bindTo($scope,'chats');
<ul class="menu" ng-repeat="(key , value) in chats">
Let say you have charts json as:
$scope.chats = [
{item: 'a', created : '2016-12-01', num :1},
{item: 'b', created : '2015-12-01' , num :4},
{item: 'c', created : '2018-12-01', num :5},
];
To sort item , you need to provide filter orderBy : sortItem : true as in
<ul ng-repeat="(key, value) in chats | orderBy : sortItem : true">
<li>{{value}} :: {{value.created}}</li>
</ul>
Your controller will have function sortitem which will tell the sorting item function
Conrtoller
$scope.sortItem = function(d) {
var dateing = new Date(d.created);
return dateing;
};
Play around jsfiddle : http://jsfiddle.net/agjqN/688/

Angularjs filter complex JSON by array

I'm having a dropdown list with multiselect option. I want to filter out data from a complex JSON based on that array.
Selected options forms a array of data like:
$scope.myval=["Adyar","Paris","central"];
My JSON :
$scope.myTest={
"buslist":
{
"code":"1",
"message":"Success",
"fromStationCode":"71",
"searchResult":[ {
"arrivalTime":"17:00:00",
"availableSeats":"42",
"boardingPointDetails":[{
"code":"1631",
"name":"Koyambedu",
"time":"09:30:00"
},
{
"code":"961296",
"name":"Paris",
"time":"09:45:00"
}
]
]
},
{
"arrivalTime":"18:00:00",
"availableSeats":"32",
"boardingPointDetails":[{
"code":"2084",
"name":"Adyar",
"time":"09:30:00"
},
{
"code":"961296",
"name":"Madurai",
"time":"09:45:00"
}
]
]
}
}
...
};
My HTML templating is:
<tbody ng-repeat=" i in myTest.buslist.searchResult" >
<tr>
<td>{{i.arrivalTime}}</td>
<td>{{i.availableSeats}}</td>
<td>
<p ng-repeat="m in i.boardingPointDetails">{{m.name}}</p>
</td>
</tr>
</tbody>
I want to filter my data based on selected values. I had tried something like this :
$scope.matched = $scope.myTest.buslist.searchResult.boardingPointDetails.name.indexOf(data);
i.e:selected options must match "name" field in "boardingPointDetails" but it fails. Thanks in advance.
Since $scope.myTest.buslist.searchResult.boardingPointDetails is an array
$scope.myTest.buslist.searchResult.boardingPointDetails.name is not valid.
You need to use an Array function to get the correct result:
$scope.matched = $scope.myTest.buslist.searchResult.boardingPointDetails.filter(function(el) {
return el.name === data;
}).length > 0;
EDIT:
Due to your comments I understand you want to get the boardPointDetails that has the same name property as one of the data options. Where data is an Array of strings.
This will do the job:
$scope.matched = $scope.myTest.buslist.searchResult.boardingPointDetails.filter(function(el) {
return data.indexOf(el.name) === 1;
});

ng-repeat in angularJs avoid duplicate values

I have object like this
{
{
"assetId" : "560",
"assetName" : "Testname",
"message" : "hai",
"timestamp" : 1452585984181
},
{
"message" : "haii",
"timestamp" : 1452585999592
},
{
"assetId" : "560",
"assetName" : "Testname",
"message" : "heloo",
"timestamp" : 1452586221604
}
}
show to this object i am using ng-repeat. My question is
I need to show all message using ng-repat comes under single assetName. but in this object two objects have same assetName and assetId. i need to show the messages both same objects but no need to repeatably show the assetName in top.
How can i only avoid the duplicate assetName and assetId. I used
<div class="container" data-ng-repeat="data in dataList | unique:'assetId'">
But it's completely removing the object. I need the message from all objects.
is it possible.Please help
This is the out put i am expecting.:
I think you should create your own custom filter
yourApp.filter('customuniqueFilter', function() {
return function( array, propertyThatMustBeUnique) {
var newArray = [];
for (i = 0; i++; i < array.length){
if ( notYetInYourArray ){ // I was too lazy to think about a way to do it ;-) feel free to update my answer
newArray.push(array[i]);
}
}
return newArray;
}
});
and then use it like this :
<div class="container" data-ng-repeat="data in dataList | customunique:'assetId'">
How about this:
<div class="container" data-ng-repeat="data in dataList | unique:'assetId'">
<span>{{data.assetId}}</span>
<div data-ng-repeat="data2 in dataList | filter:(data.assetId === undefined ? {assetId:'!'} : data.assetId)">
<span>{{data2.message}}</span>
</div>
</div>

AngulaJS filter on array of object

I have this JSON object.
var UsersList=[
{
"User" : {
"IdUser" : "admin",
"FirstName" : "mirco",
"LastName" : "sabatino"
}
}, {
"User" : {
"IdUser" : "coordinator",
"FirstName" : "coordinator",
"LastName" : ""
}
}, {
"User" : {
"IdUser" : "test",
"FirstName" : "publisher",
"LastName" : "Diaz"
}
}, {
"User" : {
"IdUser" : "work",
"FirstName" : "ingester",
"LastName" : "Brown"
}
}
] ;
I want filter in ng-repeat for LastName value.
<div class="col-md-6" ng-repeat="users in UsersList | filter: {User.LastName : filterSearchLetter}">
filterSearchLetter value in my controler is populated by
$scope.filterLetterUser=function(letter){
$scope.filterSearchLetter=letter;
console.log($scope.filterSearchLetter);
};
But this don't work.
See my plnkr for the solution http://plnkr.co/edit/l27xUQ?p=preview. I also have implemented your required UI behavior using ng-change. Hope it helps.
For detailed explanation I offer you Todd Motto's blog - http://toddmotto.com/everything-about-custom-filters-in-angular-js/
To invoke a filter, the syntax is the filter function name followed by the parameters.
To define a filter you need to do (This is copy of Todd Motto's code modified for your data)
todos.filter('startsWithLetter', function () {
return function (items, letter) {
var filtered = [];
var letterMatch = new RegExp(letter, 'i');
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (letterMatch.test(item.User.LastName.substring(0, 1))) {
filtered.push(item);
}
}
return filtered;
};
});
This is not a valid object: {User.LastName : filterSearchLetter} It should actually throw an exception saying something like
Uncaught SyntaxError: Unexpected token .
What you probably want to try instead is: {"User": {"LastName" : filterSearchLetter} }
To iterate over an array of Objects see:
angularjs - ng-repeat: access key and value from JSON array object
You may have to convert to valid JS object using JS_Obj=JSON.parse(JSON_Obj);
Maybe something like this:
//iterate through array
<ul ng-repeat="users in UsersList">
//iterate through Object
<li ng-repeat=(key, value) in users | filter: {User.LastName : filterSearchLetter}>
{{key}} : {{value}}
</li>
</ul>

Resources