I have a array of object values.i am using a group by method to group the values based on type.it gives a object of array values.i struggle to how to display the values using Ngfor in angular 2.
i have a following structure value.
{
[
{
id:1
body:"value1"
type:"name"
},
{
id:2
body:"value1"
type:"id"
}
],
[
{
id:3
body:"value1"
type:"name"
},
{
id:4
body:"value1"
type:"id"
},
{
id:5
body:"value1"
type:"name"
}
],
[
{
id:6
body:"value1"
type:"id"
},
{
id:7
body:"value1"
type:"fname"
},
{
id:8
body:"value1"
type:"fname"
}
]
}
And my html code is.
<div *ngFor="let value of result">
{{value.body}}
</div>
ngFor only works on Array element. Also your current JSON seems to invalid. Though You can easily flatten the arrays into single array and use ngFor to render it on DOM
<div *ngFor="let value of flattenArray">
{{value.body}}
</div>
Component
flattenArray = [];
//after retrieving result, create flatten array.
for(let value of result){
this.flattenArray.conact(value);
}
what you have is not an array of objects, it's even not a JSON (check it with https://jsonlint.com/),
when you replace first {} with [], (and add comas, ofcourse!) all will works fine, here is valid json:
[
[
{
id:1,
body:"value1",
type:"name"
},
{
id:2,
body:"value1",
type:"id"
}
],
[
{
id:3,
body:"value1",
type:"name"
},
{
id:4,
body:"value1",
type:"id"
},
{
id:5,
body:"value1",
type:"name"
}
]
]
and then in angular view:
<div *ngFor="let items of result">
<div *ngFor="let value of items">
{{value.body}}
</div>
</div>
Thanks for everyone response.i got a solution for the question.
let value = _.groupBy(data, "type");
for (let key in value) {
content.push({ key: key, value: value[key] });
}
and my html is
<div *ngFor="let keys of content">
<div *ngFor="let value of keys.value">
{{value.body}}
</div>
</div>
Related
how can I get the information from this json to paint them in angular 10
{
"countries": [
{
"id": 1,
"name": "United States"
},
{
"id": 2,
"name": "India"
}
],
"states": [
{
"id": 1,
"countryId": 1,
"name": "Alabama"
},
{
"id": 2,
"countryId": 1,
"name": "Alaska"
}
]
}
for normal jsons I used this one, but that jeson has 2 arrays and it won't let me
return this.http.get<Country[]>("./assets/data.json");
Error trying to diff '[object Object]'. Only arrays and iterables are allowed
<!-- html -->
<div *ngFor="let item of countri">
{{item.id}}
</div>
model
export interface Country {
id: number;
name: string;
}
and my subscribe
countri: Country[] = [];
this.countriesService.getCountries().subscribe(
countri => {
this.countri = countri;
console.log(countri);
},
err => console.log(err)
);
Use any.
1st way:
return this.http.get<any>("./assets/data.json");
2nd way define an proper interface for your data.
export interface IRequest {
countries: ICourtry[],
states: IState[]
}
export interface ICourtry{
id:number;
name: string;
}
export interface IState{
id:number;
name: string;
countryId: number;
}
return this.http.get<IRequest>("./assets/data.json");
This mentioned error(Error trying to diff '[object Object]') are because you are using this json somewhere in your template but it has no values. Hope it will fix it or provide the template code also.
Error trying to diff '[object Object]'. Only arrays and iterables are allowed , this error usually comes when you try to iterate through ngFor with an Object instead of an Array.
If you are using ngFor,
list.component.ts
data={
"countries": [
{
"id": 1,
"name": "United States"
},
{
"id": 2,
"name": "India"
}
],
"states": [
{
"id": 1,
"countryId": 1,
"name": "Alabama"
},
{
"id": 2,
"countryId": 1,
"name": "Alaska"
}
]
}
list.component.html
<ul>
<li *ngFor="let item of data.countries">
{{item.name}}
</li>
</ul>
or
<ul>
<li *ngFor="let item of data.states">
{{item.name}}
</li>
As the error suggests, you are most likely trying to iterate over an object rather than an array. Also, since the data you fetch is asynchronous you may make use of the following code to avoid any errors. It makes use of the async pipe along with the safe(?) operator.
.ts
jsonData;
ngOnInit() {
this.jsonData = this.http.get('./assets/data.json');
}
template
<div *ngFor="let country of (jsonData | async)?.countries">
{{ country | json}}
</div>
<div *ngFor="let state of (jsonData | async)?.states">
{{ state | json}}
</div>
I have a JSON which comes back like this from a API call:
"free_seat_blocks": {
"blocks_by_row": {
"22": [
[
"2218"
]
],
"23": [
[
"2315",
"2316",
"2317",
"2318"
]
],
"24": [
[
"2411",
"2412",
"2413",
"2414",
"2415",
"2416",
"2417",
"2418"
]
]
},
}
How can I access the name of the array (i.e 22, 23, etc) in ReactJs. I need to use the name of the array to display the seat Row in table format.
Update:
I want to get the values of the keys also and display them like below -
Row Seat Number
22 2218
23 2315,2316,2317,2318
24 2411,2412,2413,2415,2416,2417,2418
You can use Object.keys() to get the key names of the blocks_by_row object.
const keys = Object.keys(free_seat_blocks.blocks_by_rows); // Will return an array ['22', '23', '24'];
blocks_by_row is an object and you want to access the key names. There are multiple ways of doing the same.
If you just want to display the name (keys) of blocks_by_keys object, use Object.keys on it, it will return an array of all the key names.
Like this:
let data = {
"free_seat_blocks": {
"blocks_by_row": {
"22": [
[
"2218"
]
],
"23": [
[
"2315","2316","2317","2318"
]
],
"24": [
[
"2411","2412","2413","2414","2415","2416","2417","2418"
]
]
},
}
}
var App = () => {
return(
<div>
<table>
<tr>
<td>Rows</td>
<td>Seat No</td>
</tr>
{
Object.entries(data.free_seat_blocks.blocks_by_row).map(([row, seats]) => <tr key={row}>
<td>{row}</td>
<td>{seats.join(',')}</td>
</tr>)
}
</table>
</div>
)
}
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>
I'm tryin to use a select with ng-options to populate my dropdown. This is my JSON
{
"Food": [
{
"Name": Apple,
"HealthCondition": [
{
"Name": "High Blood Pressure",
"Eat": null
},
{
"Name": "High Cholesterol",
"Eat": null
},
{
"Name": "Heart Disease",
"Eat": null
},
{
"Name": "Osteoporosis",
"Eat": null
},
{
"Name": "Digestive Disorder",
"Eat": null
}
]
}
And this is my select <select class="chosen-select" ng-model="selectedValue" ng-options="x.HealthCondition for x in myResults.Food" multiple chosen></select> and the result I'm getting is [object Object],[object Object],[object Object],[object Object],[object Object]
I'm trying to get a list of the Health Condition Names! Any help would be greatly appreciated. Stumped on this for hours. I'm using the Angular Chosen directive. This is working correctly if I just use the Name field like x.Name but I want to get HealthCondition Name.
Any help would be greatly appreciated!
Some Observations :
Your JSON is not valid. Apple should be a string against the name key.
You are iterating the Food array in ng-options it should be HealthCondition.
DEMO
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope) {
$scope.jsonObj = {
"Food": [
{
"Name": "Apple",
"HealthCondition": [
{
"Name": "High Blood Pressure",
"Eat": null
},
{
"Name": "High Cholesterol",
"Eat": null
},
{
"Name": "Heart Disease",
"Eat": null
},
{
"Name": "Osteoporosis",
"Eat": null
},
{
"Name": "Digestive Disorder",
"Eat": null
}
]
}]};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<select class="chosen-select" ng-model="selectedValue" ng-options="x.Name as x.Name for x in jsonObj.Food[0].HealthCondition" multiple chosen></select>
</div>
Try <select class="chosen-select" ng-model="selectedValue" ng-options="x.Name as x.Name for x in myResults.Food.HealthCondition" multiple chosen></select>
The issue is that your data is not able to be used for ng-options in its current format. You need to reduce the available HealthConditions down into a single array instead of multiple objects with a HealthCondition array as a property.
In your controller you will need to map the data to a single array like so:
$scope.HealthConditions = myResults.reduce(function(arr, result){
for(var i in result.HealthCondition){
arr.push(result.HealthCondition[i]);
}
return arr;
}, []);
And then in your view use the following:
<select class="chosen-select" ng-model="selectedValue" ng-options="x.Name for x in HealthConditions" multiple chosen></select>
I am new to angular. I have a json object:
[
{
"id": 1,
"name": "name1",
"speciality": "speciality1",
"address": "address1",
"phoneNumber": 9999999999
},
{
"id": 2,
"name": "name2",
"speciality": "speciality2",
"address": "address2",
"phoneNumber": 9999999999
},
...
]
and I want to filter based on two properties: name and speciality. This search is matching insensitive substring. How to do this? The way I am doing this is as follows, which doesn't work:
$filter('filter')(doctor.details, { $: query }, false, [name, speciality]);
$filter('filter')(doctor.details, { name: query } || {speciality : query }, false);
doctor.details is the json object array, query is the (sub)string to be matched with name or speciality.
You can write a AngularJS filter to filter out the list based on query matching name and speciality properties.
app.filter('filterDetails', function() {
return function(details, query) {
var filteredDetails = [];
filteredDetails = details.filter(function(obj) {
// look whether query is substring of name or speciality
if (~obj.name.indexOf(query) || ~obj.speciality.indexOf(query)) {
return obj;
}
})
// finally return filtered array
return filteredDetails;
};
});
HTML
Query :
<input type="text" ng-model="query" />
<ul>
<li ng-repeat="detail in doctor.details | filterDetails:query">
{{ detail }}
</li>
</ul>
Plunker
Did it using lodash as this was the easiest I could think of:
_.union($filter('filter')(doctor.details, { name: query }), $filter('filter')(doctor.details, { speciality: query }));
If I have a dataset that contains an array of objects, with each object having an array inside of them, how can I sort the subarrays by their properties? For example, here is some sample music data, it has 2 albums with tracks within them:
albums: [
{
type: "album",
name: "Brothers",
tracks: [
{
type: "track",
name: "Everlasting Light"
},
{
type: "track",
name: "Next Girl"
},
{
type: "track",
name: "Tighten Up"
}
]
},
{
type: "album",
name: "Listen",
tracks: [
{
type: "track",
name: "Around Town"
},
{
type: "track",
name: "Forgive & Forget"
}
]
}
]
The result would look like this:
- Around Town
- Everlasting Light
- Forgive & Forget
- Next Girl
- Tighten Up
Is there any way I can use an ng-repeat to create an alphabetically sorted list of music tracks?
I'd imagine it working something like below, but I tried with no success.
<p ng-repeat="track in albums.tracks">{{track.name}}</p>
Since you need only the tracks of albums, you should merge all the tracks in a single array and then just sort it alphabetically. Here's is a snippet working:
var app = angular.module('app', []);
app.controller('mainCtrl', function($scope) {
$scope.albums = [
{
"type":"album",
"name":"Brothers",
"tracks":[
{
"type":"track",
"name":"Everlasting Light"
},
{
"type":"track",
"name":"Next Girl"
},
{
"type":"track",
"name":"Tighten Up"
}
]
},
{
"type":"album",
"name":"Listen",
"tracks":[
{
"type":"track",
"name":"Around Town"
},
{
"type":"track",
"name":"Forgive & Forget"
}
]
}
];
$scope.tracks = [];
angular.forEach($scope.albums, function(value) {
$scope.tracks = $scope.tracks.concat(value.tracks);
});
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js">
</script>
</head>
<body ng-controller="mainCtrl">
<div ng-repeat="track in tracks | orderBy:'name'">
<span ng-bind="track.name"></span>
</div>
</body>
</html>
You can use the orderby filter to sort your list based on a property. The angular website has more info on this https://docs.angularjs.org/api/ng/filter/orderBy
Here is a plunker that might help, https://plnkr.co/edit/goxNA9PvBeFL0hyWp9hR?p=preview
You can use the filter directly in your html to sort by a property.
<div ng-repeat="album in albums">
<h2>{{album.name}}</h2>
<div ng-repeat="track in album.tracks | orderBy:'name'">
{{track.name}}
</div>
</div>