Angular: Dynamically find headers when converting JSON array to HTML table - json

In Angular, I want to convert a JSON array to an HTML table.
I have seen an old answer for AngularJS:
<table>
<thead>
<tr>
<th ng-repeat="(key, value) in records[0]">{{key}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(key, value) in records">
<td ng-repeat="(key, value) in value">
{{value}}
</td>
</tr>
</tbody>
</table>
JSON looks like this:
[{
"Name": "Alfreds Futterkiste",
"City": "Berlin",
"Country": "Germany"
}, {
"Name": "Berglunds snabbköp",
"City": "Luleå",
"Country": "Sweden"
}, {
"Name": "Centro comercial Moctezuma",
"City": "México D.F.",
"Country": "Mexico"
}]
I've tried to translate it to the Angular syntax. Here is what I got so far:
<table>
<thead>
<tr>
<th *ngFor="let item of records[0] | keyvalue">{{item.key}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of records">
<td *ngFor="let item1 of item | keyvalue">
{{item1.value}}
</td>
</tr>
</tbody>
</table>
Right now it's failing to compile because records[0] is undefined... how can I translate this expression to the newer syntax (or create something equivalent)?
UPDATE 1:
I have a partial solution. However with this partial solution the rendered table is not completely identical to the older AngularJS rendition (because it creates multiple unnecessary header rows, which only one of them is populated, as opposed to only one header row in the older rendition).
<table style="border-collapse: collapse;">
<thead *ngFor="let item of records; let last=last">
<tr *ngIf="last">
<th *ngFor="let item1 of item | keyvalue">
{{item1.key}}
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of records">
<td *ngFor="let item1 of item | keyvalue">
{{item1.value}}
</td>
</tr>
</tbody>
</table>
Do you have a better way to do it, possibly similar to the older AngularJS version?
UPDATE 2:
In Angular, I access the JSON data through a request from Angular that is then redirected to a back end service. That service may read a file, or get the data from a database. When the back end service has the data ready, it returns the data to the Angular request. The code on the Angular end looks like this:
HTML:
<div>
<h3>Test Post Request</h3>
<button (click)="postData()">Click Me</button>
<div>Response: {{records}}</div>
</div>
TypeScript:
private dataPostTestUrl = '/api/postTest';
records: string | undefined;
public postData(): void {
this.appService.sendData().subscribe((data: any) => {
this.records = data.content;
});
}
public sendData(): Observable<any> {
return this.http.post(this.dataPostTestUrl, {});
}

I think maybe you need to define records in the component.
records = [{
"Name": "Alfreds Futterkiste",
"City": "Berlin",
"Country": "Germany"
}, {
"Name": "Berglunds snabbköp",
"City": "Luleå",
"Country": "Sweden"
}, {
"Name": "Centro comercial Moctezuma",
"City": "México D.F.",
"Country": "Mexico"
}];

I am fairly certain this is what you need: https://stackblitz.com/edit/angular-ivy-n7irpw?file=src/app/hello.component.ts
Take a look at how I import the file in the app.component.ts
As well as how I loop in the HTML.
Let me know if it helps!

Related

Filling a table with JSON data

I am taking mmy first steps in Angular and was about to try populating a table with data stored in a JSON file. Facing a bit of an odd/unexpected situation there as the table doesn't look exactly how I expected it to look. First things first.
Table code:
<table class="table table-sm table-bordered">
<thead>
<tr>
<th>Transfers</th>
<th>Tools</th>
</tr>
</thead>
<tbody>
<tr *ngFor = "let data of linksArray">
<td>{{ data.Transfers}}</td>
<td>{{ data.Tools}}</td>
</tr>
</tbody>
</table>
What I would like to achieve is that the columns Transfers and Tools get filled with data that uses the corresponding keywords in my JSON file. And here it is
[{"Type":"Transfers","Name":"1","Hyperlink":"#"}, {"Type":"Transfers","Name":"2","Hyperlink":"#"},
{"Type":"Tools","Name":"1","Hyperlink":"#"}, {"Type":"Tools","Name":"2","Hyperlink":"#"}]
The array gets loaded by using this in my .ts file
this.http.get('../../assets/templatefiles/links.json').subscribe(data => {this.linksArray = data as
any [];
console.log(this.linksArray);
},
(err: HttpErrorResponse) => {
console.log (err.message);
}
);
So far all looks good, I see the array popping up in console, but then look at the table and am confused
I would have expected the entries in the 2nd column to start in the first cell. Instead they start in the 3rd? What am I missing here? Been marveling for quite a while now :)
https://stackblitz.com/edit/angular-ivy-hvcyfq
To get this
Transfers Tools
1 10
2 20
You want code roughly like this
<hello name="{{ name }}"></hello>
<table class="table table-sm table-bordered">
<thead>
<tr>
<th>Transfers</th>
<th>Tools</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of linksArray">
<td>{{data.Transfers.Name}}</td>
<td>{{data.Tools.Name}}</td>
</tr>
</tbody>
</table>
And, this is the main bit, json roughly like this
linksArray = [
{
Transfers: {
Name:"1",
Hyperlink:"#"
},
Tools: {
Name:"10",
Hyperlink:"#"
}
},
{
Transfers: {
Name:"2",
Hyperlink:"#"
},
Tools: {
Name:"20",
Hyperlink:"#"
}
},
Your existing json looks like this, where the '{' represents one row
[
{
"Type":"Transfers",
"Name":"1",
"Hyperlink":"#"
},
{
"Type":"Transfers",
"Name":"2",
"Hyperlink":"#"
},
{
"Type":"Tools",
"Name":"1",
"Hyperlink":"#"
},
{
"Type":"Tools",
"Name":"2",
"Hyperlink":"#"
}
]

How to iterate a JSON array in typescript in HTML?

I have a snippets of JSON array as shown below:
[{
"auction_number": "015",
"email": "pete#abc.com",
"first_name": "Peter",
"last_name": "Dan",
"table": 0,
"id": "015"
},
{
"auction_number": "024",
"email": "dan#gog.com",
"first_name": "Dan",
"last_name": "Fain",
"table": 0,
"id": "024"
}
]
Typescript Code:
The typescript (ts) for the above JSON array is shown below. Here attendees is an array object.
attendees: Attendee[];
constructor(public authService: AuthService) {
const str = localStorage.getItem("attendees");
if(str) {
this.attendees = JSON.parse(str);
console.log(str);
}
}
HTML Code:
The HTML code which I have used in order to iterate everything from the JSON array (in the typescript code) is shown below. For some reasons, it is not able to iterate attendees in the HTML.
<tr *ngFor="let row of attendees">
<td class="left">{{ attendees.first_name }} {{ attendees.last_name }}</td>
<td class="number1">250</td>
<td class="table1">{{attendees.table}}</td>
<td class="right-bill">Bill</td>
</tr>
Problem Statement:
I am wondering what changes I should make in the HTML code above so that I am successfully able to iterate attendees array. I tried using ngfor directive but somehow it didn't work.
You should reference fields in each row as row.first_name because you set each attendee as let row of attendees. The variable you defined is row.
You are accessing the parent loop again, you should access only the elements of row
<tr *ngFor="let row of attendees">
<td class="left">{{ row .first_name }} {{ row .last_name }}</td>
<td class="number1">250</td>
<td class="table1">{{attendees.table}}</td>
<td class="right-bill">Bill</td>
</tr>

Unable to iterate *ngFor loop with array of column in table

I have table like this which i want to iterate
Heating Diesel Benzin Fracht
43.10 87.15 108.00
43.35 87.40 108.25
43.80 87.80 108.60 2394.00
----- ----- ----- ----
Here is json data which i want to insert into my table and here first object is one column, second object is second column like that i need to insert 4 columns. i don't understand how to iterate this with *ngFor loop. please excuse if any thing wrong in my question.
[
{
"s4": "43,10",
"s5": "43,35",
"s6": "43,80",
"s7": "43,90",
"s8": "44,10",
"s15": "64,25",
"s9": "44,55",
"s10": "43,20",
"s11": "43,90",
"s16": "54,00"
},
{
"s4": "87,15",
"s5": "87,40",
"s6": "87,80",
"s7": "87,90",
"s8": "88,05",
"s15": "121,05",
"s9": "88,60",
"s10": "87,30",
"s11": "88,00",
"s16": "80,90"
},
{
"s4": "108,00",
"s5": "108,25",
"s6": "108,60",
"s7": "108,70",
"s8": "108,85",
"s15": "119,65",
"s9": "109,30",
"s10": "108,50",
"s11": "109,00",
"s16": "92,25"
},
{
"s4": "",
"s5": "",
"s6": "2394,02",
"s7": "12,29",
"s8": "2395,46",
"s15": "",
"s9": "2386,92",
"s10": "22:05",
"s11": "",
"s16": ""
}
]
<table *ngIf="indexdata">
<tr style="color: #3B6593" >
<th><strong>Heizöl</strong></th>
<th><strong>Diesel</strong></th>
<th><strong>Benzin</strong></th>
<th><strong>Facht</strong></th>
</tr>
<tr *ngFor="let index of indexdata;let i=index">
<td>{{index.s4}}</td>
<td>{{index.s5}}</td>
<td>{{index.s6}}</td>
-----
-----
</tr>
</table>
Your code should be
<table *ngIf="indexdata">
<tr style="color: #3B6593">
<th><strong>Heizöl</strong></th>
<th><strong>Diesel</strong></th>
<th><strong>Benzin</strong></th>
<th><strong>Facht</strong></th>
</tr>
<tr>
<td *ngFor="let indexvalue of indexdata">
<table>
<tr *ngFor="let indexobj of indexvalue | keys">
<td>
{{indexobj.value}}
</td>
</tr>
</table>
</td>
</tr>
</table>
You could create a custom pipe to return the list of key for each element. Something like this:
#Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]});
}
return keys;
}
}

How to convert a JSON file to another JSON file with different approach in React

I have a JSON file like this:
[
{
"quantity": "200",
"prodType": "stock",
"symbol": "LOL",
"prodDesc": "Εθνική τράπεζα",
"market": "Greece",
"averageCost": "131,16",
"totalCost": "123,47",
"lastPrice": "121,123",
"value": "123,34",
"positionPercentage": "10",
"valueEUR": "113,23",
"pl": "1300",
"plPercentage": "12",
"plEuro": "1238",
"results": "12-01-2017",
"dividend": "12-03-2017",
"isin": "1234566"
}
]
Then, I create a table with the following format:
Quantity Product Type Symbol Product Desc Market Average Cost
200 stock LOL ET Greece 131,16
But I want to display the table above with the following format:
Quantity Product Type Product Desc Market Average Cost
Symbol
200 stock ET Greece 131,16
LOL
I think that the best way is to create a JSON file from the fiven JSON above with the desired format. Do you know how I can do this?
If I understand well, it should be sth like that:
var obj = JSON.parse(yourJsonFile);
return <table>
<tr>
<th>Quantity<br/>Symbol</th>
<th>Product Type</th>
<th>Product Desc</th>
<th>Market</th>
<th>Averate Cost</th>
</tr>
<tr>
<td>{obj.quantity}<br/>{obj.symbol}</td>
<td>{obj.prodType}</td>
<td>{obj.prodDesc}</td>
<td>{obj.market}</td>
<td>{obj.averageCost}</td>
</tr>
</table>
You can write this in a generic way, it will populate all the rows, if u have more data, Try this:
_getTableData(){
return this.state.currentValue.map((obj, index)=>
<tr key={index}>
<td>{obj.quantity}<br/>{obj.symbol}</td>
<td>{obj.prodType}</td>
<td>{obj.prodDesc}</td>
<td>{obj.market}</td>
<td>{obj.averageCost}</td>
</tr>
);
}
render() {
return
<table>
<tbody>
<tr>
<th>Quantity<br/>Symbol</th>
<th>Product Type</th>
<th>Product Desc</th>
<th>Market</th>
<th>Averate Cost</th>
</tr>
{this._getTableData()}
</tbody>
</table>
}
Check the working code on jsfiddle: https://jsfiddle.net/qswordh3/

How to iterate through a list which is in another list in thymeleaf?

I'm new in thymeleaf. i'm stuck in one place where i need to iterate through a list of strings which is present inside another list. For example, ihave a json like this :
{
"_id" : ObjectId("54e1865423asgj086"),
"Name" : "Carbon Utility",
"Modified In " : "DEC 5th",
"Imported" : "N",
"Classification" : "Functional SW delivery",
"Type Designation" : "Heavy Use",
"StateList" : [
{
"name" : "Create",
"currentStatus" : "False",
"stateDuration" : "336264 "
},
{
"name" : "Implement",
"currentStatus" : "False",
"stateDuration" : "1393827 "
},
{
"name" : "RampUp",
"currentStatus" : "False",
"stateDuration" : "34 "
},
]
}
in my Controller, i'm adding this to a object.
#RequestMapping(value = "/Search1", method = RequestMethod.GET)
public String showEntity( #RequestParam("type") String typeNameid,Model model,HttpSession session) {
------ my other stuffs--------
---- here i'm getting data from other html and spliting to add to model----
model.addAttribute("resultSourceDbObject",migrationSourceDataBean.getResultSourceDbObject());
return "wipdm/Display";
}
Now, in my html page. I'm able to print the id,name and type desgination. but i'm stuck in iterating through the statelist. For each statelist i have to create a separate subfolder inside a table and need to display the name,status and duration. I'm trying this but not working.
<table id="example-advanced" class="table table-striped table-bordered table-hover" style=" font-size:1.1em;">
<thead class="dark-border-bottom">
<tr>
<th style="text-align:center"> Key</th>
<th style="text-align:center">Values</th>
</tr>
</thead>
<tbody>
<tr data-tt-id='1'><td><span class="file"> Type</span></td><td><span th:text="${resultSourceDbObject.getString('Type Designation')}"></span> </td></tr>
<tr data-tt-id='1'><td><span class="file"> Name</span></td><td><span th:text="${resultSourceDbObject.getString('Name')}"></span> </td></tr>
<tr data-tt-id='1'><td><span class="file"> id</span></td><td><span th:text="${resultSourceDbObject.getString('_id')}"></span> </td></tr>
<tr data-tt-id='2'><td><span class='folder'>Statelist</span></td><td></td></tr>
<tr data-tt-id='2-1' data-tt-parent-id='2' th:each="relresult : ${resultSourceDbObject.getString('StateList')}"><td><span class='folder' th:text="Relationship" >Relationship</span></td><td>Folder</td></tr>
<tr data-tt-id='2-1-1' data-tt-parent-id='2-1'><td><span class='file' >name</span></td><td th:text="${relresult.getString('name')}">Release</td></tr>
<tr data-tt-id='2-1-2' data-tt-parent-id='2-1'><td><span class='file'>currentstatus</span></td><td th:text="${relresult.getString('currentStatus')}">132456424</td></tr>
<tr data-tt-id='2-1-3' data-tt-parent-id='2-1'><td><span class='file'>Stateduration</span></td><td th:text="${relresult.getString('stateDuration')}">16572464</td></tr>
</tbody>
</table>
Can anybody tell me where i'm going wrong and how to acheive this.? Thanks in advance.
I'm not sure exactly what type of object migrationSourceDataBean.getResultSourceDbObject() is returning, but resultSourceDbObject.getString('StateList') won't be returning what you need. (I guess it's just giving you the JSON?)
Assuming it's something similar to JSONObject you should be calling getJSONArray() (or similar) which will give you the nested list which you can then iterate over.