ng-repeat and nested array in json - arrays

i have some problems accessing some values stored in a json with the directive ng-repeat.
the json is formatted properly (checked it with a json checker) and it's called via $http service. unfortunately i can't change the format of json, retrieved through the wordpress-json-api plugin.
the json (with some cuts):
{
"status": "ok",
"count": 10,
"count_total": 24,
"pages": 3,
"posts": [
{
"id": 108,
"type": "sensor",
"slug": "ert",
"custom_fields": {
"sensor_id": [
"er"
],
"coords": [
"{\"address\":\"\",\"lat\":55.39979700000003,\"lng\":10.430533275390644,\"zoom\":12}"
]
}
}
//etc other posts following, json correct
Now i have a problem accessing the single values inside coords. i complained too about serializing data in db, but i'd like anyway to get lng and lat out of that array
<ul>
<li ng-repeat="post in sensor.posts">
<h4>name : {{post.id}}</h4> //ok
<h4>all custom fields : {{post.custom_fields}}</h4> //good-this-too
<h4>custom field lat : {{post.custom_fields.prova_coords[0]}}</h4> //works but can't go on
</li>
</ul>
the ouput of last line is:
custom field lat : {"address":"","lat":55.39979700000003,"lng":10.430533275390644,"zoom":12}
but now i'm stuck..can't retrieve single lat and long values

You need to use $scope.$eval(coordsString)
Here's a test: http://jsfiddle.net/mikeeconroy/Rnc7R/
var objString = "{\"address\":\"\",\"lat\":55.39979700000003,\"lng\":10.430533275390644,\"zoom\":12}";
$scope.coords = $scope.$eval(objString);
Then you can refer to coords.lat or coords.lng in your template like so:
<div ng-controller="myCoordsCtrl">
Lattitude: {{coords.lat}}<br>
Longitude: {{coords.lng}}
</div>
Since this is happening within an ngRepeat you may need to use an Angular filter to rectify the string on the fly
<li ng-repeat="post in sensor.posts | myRectifyCoordsFilter">
EDIT:
Don't use the filter like in the above example, using filters to modify $scope is not a good situation. You'll need to modify your $scope prior to using it in the ng-repeat
$http.get().success(function(data){
angular.forEach(data,function(val,key){
this.coords = $scope.$eval(val.coords[0]);
},data);
$scope.sensor = data;
});

Related

How to iterate through a JSON array and display specific information based on an API response value in React?

I'm building a ReactJS web application, I have a JSON array:
[{
"2149166938": {
"name": "Classical-42",
"icon": "/common/destiny2_content/icons/e6885dab15cafeaf0dbf80f1ff9b5eb8.jpg"
},
"2149166939": {
"name": "Countess SA/2",
"icon": "/common/destiny2_content/icons/de8906743db9fce201b33802c8498943.jpg"
},
"2154059444": {
"name": "The Long Goodbye",
"icon": "/common/destiny2_content/icons/fe07633a2ee87f0c00d5b0c0f3838a7d.jpg"
}
}]
When I make a call to an API I am returned a value of lets say 2154059444 which is the same value as the last object in my JSON file.
How would I iterate through the JSON file to find the object which has a value of 2154059444 and then access and render it's child values like name or icon?
you can do something like this. Your array is not proper please edit.
Create filtered data :
//here i am addding single dummy point you can make your function
l
et filteredData = [].concat(data.map(test => {
if(Object.keys(test)[0]==="2154059444"){
return test["2154059444"]
}
})).filter(Boolean)
and simply render it app like this .
{ filteredData.map(test => <div>{test.name}</div>)}
Here is live link
This is simple. JSON is equivalent to Javascript object. So you can do something like result[0]["2154059444"]. You might want to use JSON.parse for converting the JSON string to Javascript object.

How to get the idRetainer in the listRetainerPaymentUnit?

I have a Angualr JS application and i try to get Id on my JSON im new with JSON objects.
{{detAgent[queryFilter][0][listRetainerPaymentUnit][0]}}
{
"queryFilter": [{
"objPolicyData": {"idAssign": "219","idPromotoria": "JA",
"listStatusPolicy": [{"policyStatusCode": "V"}],
"collectionType": {"DxN": true},
"listRetainerPaymentUnit": [{"idRetainer": "100","nameRetainer": "RETAINER","idPaymentUnit": "109","namePaymentUnit": "PAYMEMT UNIT"}],
"listFederalEntity": [{"idFederalEntity": "MEX","nameFederalEntity": "CDMX"}],
"listZipCode": ""
},
"policyDataInfo": {
"policyNumber": "100",
"sizeOfFullPolicyDataObject": 480,
"unitSizeFullPolicyDataObject": "MB"
}
}]
}
I expect to obtain the data with a tag Id
Resolve i remove the ng-repeat directive in the html and to get the id I only pass the variable
<div class="col-3 text-left"><label>Id {{agentsDetailList.queryFilter[0].objPolicyData.idAssign}}</label></div>

ng-repeat filter on json object

I have a complex JSON structure as below:
My JSON object is like -
$scope.data = {
"Test 1": [
{
"paperName": "Physics Test",
"lkExamTypePk": 1,
"paperPK": "20",
"lkExamType": 2
}
],
"Test 2": [
{
"paperName": "Maths Test",
"lkExamTypePk": 2,
"paperPK": "23",
"lkExamType": 3
}
]
}
I am using this json to display in my html page and want to search key which is Test 1, Test 2, etc:
<input ng-model="filter.key" />
<table>
<tr ng-repeat="(key,val) in controllerName.data | filter:filter.key">
<td>
{{key}}
</td>
</tr>
</table>
But the problem is that filter works on array and on the values of JSON and I am getting error of not an array.
Error which I'm getting at the console
Error: [filter:notarray]
I think you problem is in how you refer your variabile. As I can see you are declaring your data array into $scope variabile with
$scope.data = { ... }
Then you try to access it referring to your controller with
controllerName.data
You can follow 2 different approaches, but you can't mix them.
1) $scope variabile
If you want to work into $scope, in your controller you must declare your variabile as follow:
$scope.data = { ... }
then into html you must refer to it like this (without controllerName):
<tr ng-repeat="(key,val) in data | filter:filter.key">
2) controller scope
If you want to work into controller's scope, in your controller you must declare your variabile as follow:
this.data = { ... }
then into html you can refer to it like this:
<tr ng-repeat="(key,val) in controllerName.data | filter:filter.key">
Hint
Generally a good practice, when you receive an error referring to a variable, is to print your variable's data into html to check that you are referring well to it, something like:
<pre>{{ data | json }}</pre>
Try with array instead of object
You can try using an array intead of a json object, as suggested by the error, something like this:
$scope.data = [
"Test 1": [{
"paperName": "Physics Test",
"lkExamTypePk": 1,
"paperPK": "20",
"lkExamType": 2
}],
"Test 2": [{
"paperName": "Maths Test",
"lkExamTypePk": 2,
"paperPK": "23",
"lkExamType": 3
}]
]

angularjs filter multidimensional object json

I wnt to use ng-repeat to display a list filtered by an object value. Here is a plukr of my attempt https://plnkr.co/edit/vD4UfzM4Qg7c0WGTeY18?p=preview
The following returns all of my JSON names as expected.
<li ng-repeat="item in collection_data">{{navitem.name}}</li>
now i want to filter and only show the names of the items that have "foreign_lang": "es", like in this json snippet
{
"id": "ddb06ba2-6348-4d45-9e63-a6fa3632e5c2",
"created_at": "2015-10-12T18:34:15.668Z",
"updated_at": "2016-04-14T15:55:37.433Z",
"custom_attributes": {
"Display Name": "Activos en EspaƱol",
"foreign_lang": "es",
"display_boxes": "false"
},
},
so i made this filter function
$scope.filterByDisplay = function() {
$filter('filter')($scope.collection_data, ['foreign_lang', 'es']);
}
and called it like this.
<li ng-repeat="item in collection_data" | filter: filterByDisplay>{{navitem.name}}</li>
I did not get any console errors but i got nothing returned.
How do I properly filter through this collection to only return items with 'foreign_lang', 'es' as a value in the json? See the plunkr to see a working example https://plnkr.co/edit/vD4UfzM4Qg7c0WGTeY18?p=preview
Third attempt (since the question was revised). Use the filter function to check each object individually, and returning only those that pass the truth test.
$scope.filterByDisplay = function(value) {
return (value.content)
&& (value.content.custom_attributes)
&& (value.content.custom_attributes.foreign_lang === "es");
}
Updated Plunk - Using Filter Function

Filter collection by child

I have the following fictional object which I'm trying to filter:
{
"0":{
"boy":{
"age":"32",
"name":"Daniel Grey"
}
},
"1":{
"boy":{
"age":"23",
"name":"John Doe"
}
}
}
And then, the ng-repeat directive looks like this:
<ul>
<li ng-repeat="person in people">{{person.boy.name}}<li>
</ul>
My question is, how do I filter people by "name"? I've tried:
<input type="text" ng-model="name">
<ul>
<li ng-repeat="person in people | filter:name">{{person.boy.name}}<li>
</ul>
... but nothing happens [ ng-model seems disconnected from the view! ].
Any response is much appreciated!
Thank you!
Updated answer as per OP's updates
Looking at your fiddle, your $scope.people is essentially an array with one big JSON object, with multiple nested boy objects. This is hard to work with. If you have control over the construction of the JSON object, I will suggest converting into an array of multiple JSON objects, which may look something like:
$scope.people = [
{
"name":"Daniel Grey",
"age":"32",
"gender": "male"
},
{
"name":"John Doe",
"age":"23",
"gender": "male"
}
];
Notice how I converted the boy key into the gender attribute.
If you really have absolutely no control over the data structure, you may have to come up with a custom filter to parse through the nested structure.
Take a look at this fiddle. A few things to pay attention to:
I have to specify people[0] in ng-repeat to retrieve the one big JSON object in your array.
The custom nameFilter searches the .boy.name attribute only.
Original Answer
If you want your filter by just name, you will have to specify the specific attributes in your ng-model directive. So in your case, it will be
<input type="text" ng-model="search.boy.name">
<ul>
<li ng-repeat="person in people | filter:search">{{person.boy.name}}<li>
</ul>
But first you will need to fix your JSON object.
UPDATE:
Live demo on fiddle. I did notice that the search-by-name-only filter doesn't work with angularjs 1.2.1, but works with angularjs 1.2.2.

Resources