Display key and array values using *ngFor in angular 9 - json

JSON
{
"cars":
{
"12345": [1960, 1961, 1962],
"4567": [2001, 2002]
}
}
HTML
<strong>Plate and year</strong>
<div *ngFor="let list of lists">
{{list.cars}}
</div>
I need to display like this:
Plate and year
12345- 1960, 1961, 1962.
4567- 2001, 2002.

Based on your data structure, you can achieve this using the KeyValuePipe and additional nested *ngFor. KeyValuePipe allows you to iterate over an object similar to Object.entries providing a key and value property for each item. In this case the value will be an array that you can iterate over using an *ngFor:
<strong>Plate and year</strong>
<div *ngFor="let list of lists">
<div *ngFor="let car of list.cars | keyvalue">
<div>{{car.key}} - <div *ngFor="let year of car.value">{{year}}</div>
</div>
</div>
</div>
Here is an example in action.
Hopefully that helps!

Related

Is there a way to use iteration inside an object in html in angular?

Here's how my html code is looking:
<div *ngFor="let historyArticle of historyArticles; let i=index">
<div [innerHTML]='historyArticle[i].fields.text | mdToHtml'></div>
</div>
I want to target the every object inside the historyArticle array. Writing {{i}} inside a div gives me the index number for each entry but I want to use that to target the correct text field in each entry
You don't need the i index at all in this case. historyArticle itself is the object you want:
<div *ngFor="let historyArticle of historyArticles">
<div [innerHTML]='historyArticle.fields.text | mdToHtml'></div>
</div>
Using *ngFor in Angular is basically looping through an array.
So doing :
for (let i = 0; i < this.historyArticles.length; i++) {
// do something e.g console.log(this.historyArticles[i].fields.text);
}
Is pretty much the same as :
<div *ngFor="let historyArticle of historyArticles">
<span>{{ historyArticle.fields.text }}</span>
</div>
Hope it helps you understand that in this case you don't need to use i = index
try this.
<div *ngFor="let historyArticle of historyArticles; let i=index">
<div>{{historyArticle[i].fields.text | mdToHtml}}</div>
</div>

How to display nested array object in angular api call

<div *ngFor="let item of category">
{{item.categories.categories.id}}
</div>
That's the data fetched from api. By nested array I can't display this data
How about this
<div *ngFor="let item of category">
<div *ngFor="let subItem of item.categories">
{{subItem.categories.id}}
</div>
</div>
Explanation:
As there are nested array, you have to loop over again for inner array

display multiple nested data with angular6

I'm receiving JSON data from an API which has some child objects as well. The API has a menu level and down the menu, it's having meals. What I want to do is to display meals relating to each menu under the menu
JSON from API
[{"id":6,"name":"Menu 1","serveDate":"2019-05-10","meals":[{"id":13,"name":"Rice with Stew","description":"rice","image":"","mealType":"BREAKFAST","unitPrice":5,"status":"ENABLED"}]},{"id":5,"name":"Menu 2","serveDate":"2019-06-10","meals":[{"id":13,"name":"Corn Flakes,"description":"Flakes","image":"","mealType":"BREAKFAST","unitPrice":5,"status":"ENABLED"}]},{"id":4,"name":"Menu 3","serveDate":"2019-07-10","meals":[]}]
HTML
<div *ngFor="let item of menuList">
<h2>Menu</h2>
{{item.name}} - {{item.servate}}
<h2 *ngFor="let item of menuList.meals">Meals</h2>
{{item.name}} - {{item.mealType}}
</div>
JS
getMenus() {
this.menuServices.menuList(this.pagedData)
.subscribe(
response => {
if (response && response.code === HttpStatus.OK) {
this.menuList = response.data;
}
},
);
}
Any help on how to make this work correctly the way it should work?
<div *ngFor="let menu of menuList">
<h2>Menu</h2>
{{menu.name}} - {{menu.servate}}
<h2>Meals</h2>
<ng-container *ngFor="let meal of menu.meals">
{{meal.name}} - {{meal.mealType}}
</ng-container>
</div>
Using this way you don't have to add unnecessary divs or any other html tag for looping in angular.
this is the perfect way to do nested loops without changing your html
No need to access the main list as you have your meals array in the item object.
Change HTML Code to:
<div *ngFor="let item of menuList">
<h2>Menu</h2>
{{item.name}} - {{item.servate}}
<h2>Meals</h2>
<div *ngFor="let item of item.meals">
{{item.name}} - {{item.mealType}}
</div>
</div>
When you're doing something like let item of menuList that means the item variable should be used to refer to an individual item within your loop. To avoid confusion, I'd also recommend naming these item vars for nested loops differently.
Another important thing to keep in mind that all the markup that you want to be output for each array item should be wrapped with an element with *ngFor. It's not the case with your <h2> tag being printed for each meal, but not the meal description.
Edit the template as follows:
<div *ngFor="let menuItem of menuList">
<h1>Menu</h1>
<h2>{{menuItem.name}} - {{menuItem.serveDate}}</h2>
<p>maybe description here</p>
<h3>Meals</h2>
<p *ngFor="let mealItem of menuItem.meals">{{mealItem.name}} - {{mealItem.mealType}}</p>
</div>

Getting keys and values from json in Angular

I need to get values from json (comes from merged MySQL tables).
I've tried a several solutions from previous topic but none of them worked for me.
access key and value of object using *ngFor
my JSON format is:
[
{
"idemployee":1,
"name":"Ernest",
"surename":"Pająk",
"role":"Obsługa Baru",
"employeehours":[
{
"idemployeehours":1,
"date":"2019-01-10T23:00:00.000+0000",
"quantity":8.0
}
]
}
]
and what I got is "Key: 0 and Value: " (answer from Pardeep Jain topic above)
EDIT:
this is my code:
<div *ngFor="let item of employee| keyvalue">
Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
employee comes from Angular component and gives mentioned JSON. The problem is getting nested values from "employeehours" (like quantity)
You don't need the keyvalue pipe. employeehours is an array, so you just need a nested *ngFor for the array, so example where you have stored your data in an employees array:
<div *ngFor="let emp of employees">
<p>Name: {{emp.name}} {{emp.surename}}</p>
<div *ngFor="let hour of emp.employeehours">
<p>Date: {{hour.date | date: 'shortDate'}}</p>
<p>Quantity: {{hour.quantity}}</p>
</div>
</div>
DEMO
if you run keyValue pipe on array object you got the keys as the index of the values in the array so tha why you need a nested ngFor to run keyvalue pipe on the value of the array
<div *ngFor="let item of employee">
<div *ngFor="let emp of item |keyvalue ">
Key: <b>{{emp.key}}</b> and Value: <b>{{emp.value}}</b>
</div>
</div>
demo 🔥🔥
UPDATED!
if you want to support sohow keys value of employeehours where the value is array best cases here to create a component to do all of this and use this component to render the new values like recursion
component
export class RenderComponent {
#Input() items = [];
isArray(value) {
return value instanceof Array
}
}
template
<div *ngFor="let item of items">
<div *ngFor="let obj of item | keyvalue " class="well">
Key: <b>{{obj.key}}</b> and Value: <b>{{obj.value}}</b>
<ng-container *ngIf="isArray(obj.value)">
<render [items]="obj.value"></render>
</ng-container>
</div>
</div>
demo 💣💣

AngularJS: How to get the key of a JSON Object

I am unsure if this has got anything to do with AngularJS at all and if it is only JSON related.
Anyhow, let us say that we have the following JSON:
$scope.dataSets = {
"names": ["Horace", "Slughorn", "Severus", "Snape"],
"genders": ["Male", "Female"]
}
Now, I am using the ng-repeat directive to print the above as follows:
<div ng-repeat="data in dataSets>
//Continue readig to know what I am expcting here
</div>
What I expect within the <div></div> tags is to print "name" and "genders". That is, I wish to print the keys of the JSON. I have no idea what the keys are, as in they could be anything. How can I do this?
As docs state it:
(key, value) in expression – where key and value can be any user defined identifiers, and expression is the scope expression giving the collection to enumerate.
<div ng-repeat="(key, data) in dataSets">
{{key}}
</div>
for accessing Json key-value pair from inside controller in AngularJs.
for(var keyName in $scope.dataSets){
var key=keyName ;
var value= $scope.dataSets[keyName ];
alert(key)
alert(JSON.stringify(value));
}
if dataSets is an array and not an object you first need to ng-repeat the array items and then the key or value.
<div ng-repeat="item in dataSets">
<div ng-repeat="(key, value) in item">
{{key}}
{{value}}
</div>
</div>
just my 2 cents.
For every dataSet in dataSets, print the key and then iterate through the individual items:
<div ng-repeat="(key, dataSet) in dataSets">
<div>{{key}}</div>
<div ng-repeat="value in dataSet">
{{value}}
</div>
</div>
{{dataset}} can be displayed in one go also, the array would be displayed as a comma separated list of values.