so I was finding it difficult phrasing the title of my question, what i want to do is loop through and array of objects but i dont know the property's of the object because its dynamic and coming from a db.
Below is an example of the array object:
[{
"id": 9,
"event_id": 13,
"details": {
"firstname": "Ralph",
"lastname": "Marvin",
"email_address": "ralphmarvin#email.com",
"phone_number": "0987654321"
}
}, {
"id": 10,
"event_id": 13,
"details": {
"firstname": "John",
"lastname": "X Doe",
"email_address": "john_x_doe120#xmail.com",
"phone_number": "0009876543"
}
}, {
"id": 11,
"event_id": 13,
"details": {
"firstname": "Wari",
"lastname": "Gumah",
"email_address": "gumahwarihanna#eeee.com",
"phone_number": "120029182765"
}
}]
I want to display the details part of the object in a table that looks like this:
firstname lastname email_address phone_number
and the values appropriately under each value.
An using Angular 8.
I just dont know how to use *ngFor to access properties i dont even know.
Is what am trying to do even possible, if yes then please show me how.
Thanks!.
You can iterate over object key/values as inner for loop with keyvalue pipe accessing details object.
Html:
<table>
<tr>
<th>Firstname</th>
<th>lastname</th>
<th>email_address</th>
<th>phone_number</th>
</tr>
<tr *ngFor="let listItem of yourList" >
<td *ngFor="let innerItem of listItem.details | keyvalue">
{{innerItem.value}
</td>
</tr>
</table>
populated list
yourList = [{
"id": 9,
"event_id": 13,
"details": {
"firstname": "Ralph",
"lastname": "Marvin",
"email_address": "ralphmarvin#email.com",
"phone_number": "0987654321"
}
}, {
"id": 10,
"event_id": 13,
"details": {
"firstname": "John",
"lastname": "X Doe",
"email_address": "john_x_doe120#xmail.com",
"phone_number": "0009876543"
}
}, {
"id": 11,
"event_id": 13,
"details": {
"firstname": "Wari",
"lastname": "Gumah",
"email_address": "gumahwarihanna#eeee.com",
"phone_number": "120029182765"
}
}]
you could implement some logic on a component to get a set of fields. it Would look in some way like this: (I assume that items come as #Input() to your component, but it could be another source)
#Input() items: Item[];
fields: Set<string>;
ngOnChanges(changes) {
if(!changes.items || !this.items) return;
this.fields= new Set(this.items.flatMap(item => Object.keys(item.details)))
}
and then in the template
<tr *ngFor="let item of items">
<td *ngFor="let field of fields">{{item.details[field]}}</td>
</tr>
Related
I m trying to print table with some JSON data, but I am not able to render empty array when I am using map method.
JSON DATA :
[{
"id": 6,
"firstname": "Sharon",
"lastname": "Jenkins",
"specialties": []
}, {
"id": 2,
"firstname": "Helen",
"lastname": "Leary",
"specialties": [{
"id": 1,
"name": "radiology"
}]
}, {
"id": 4,
"firstname": "Rafael",
"lastname": "Ortega",
"specialties": [{
"id": 2,
"name": "surgery"
}]
}, {
"id": 5,
"firstname": "Henry",
"lastname": "Stevens",
"specialties": [{
"id": 1,
"name": "radiology"
}]
}]
My Code :
{this.state.vets.map(vet =><tr><td>{vet.firstname}</td>
{
vet.specialties.map((subitem,i) => {
return <td>{subitem.name}</td> })}<td>EDIT</td><td id={vet.firstname}><div class="funkyradio">
Now I am getting the following error
As Sharon doesn't have a specialist, I need to print as N/A.
How can I check the specialities are empty and print N/A.
try rendering always the TD tag, like:
{
this.state.vets.map(vet =>
<tr>
<td>{vet.firstname}</td>
<td>
{vet.specialties.map((subitem,i) => {
return <span>{subitem.name}</span>
})}
</td>
<td>EDIT</td>
<td id={vet.firstname}>
<div class="funkyradio">
use conditional statment like this
{ this.state.vets.length > 0
? this.state.vets.map(()=>Your logic)
: <Your custom message/>
}
<table>
{dataJSON.map(({ id, firstname, lastname, specialties }) => {
return (
<tr>
<td> {`${firstname} ${lastname}`} </td>
<td> {specialties.map(specialty => specialty.name).join(",")} </td>
<td> <span> EDIT </span> </td>
</tr>
);
})}
</table>
Mainly for readability, instead of using the object property, I would create a separate function that will return the specialties, if any, otherwise N/A
[{
"name": "employeeOne",
"age": 22,
"position": "UI",
"city": "Chennai"
},
{
"name": "employeeTwo",
"age": 23,
"position": "UI",
"city": "Bangalore"
}
]
If I delete "Position"
key & value from the json the result should be like[
[{
"name": "employeeOne",
"age": 22,
"city": "Chennai"
}, {
"name": "employeeTwo",
"age": 23,
"city": "Bangalore"
}]
If we have list of employee in a table I want to delete all the employees position column only. How can I achieve this with JavaScript and Typescript
I tried
const output = delete employee.position
but getting an error.
var data = [{
"name": "employeeOne",
"age": 22,
"position": "UI",
"city": "Chennai"
},
{
"name": "employeeTwo",
"age": 23,
"position": "UI",
"city": "Bangalore"
}
];
data.forEach( item => {delete item.position;});
console.log(data);
You have an array of objects there. You would have to loop through the array, deleting the property in each object individually.
take a look at the delete operation
pseudo:
foreach obj in jsonArray
{
delete obj["position"];
}
also works:
obj[position]
obj.position
http://perfectionkills.com/understanding-delete/
I have the following JSON response coming from an API.
{
"status": true,
"cakes": {
"7689": {
"id": 7689,
"flavor": "chocolate",
"cookDetails": {
"id": 101,
"firstName": "Name1",
"lastName": "LastName1"
}
},
"7690": {
"id": 7690,
"flavor": "vanilla",
"cookDetails": {
"id": 102,
"firstName": "Name2",
"lastName": "LastName2"
}
}
}
}
Language I'm using to parse this JSON: Javascript
Framework: ReactNative
How do I parse it (NOTE: I don't know the value of id in cakes until I parse it)?
PS: New to the framework. Big thanks.
I am not sure about that but I think you want to somehow access a cake with id e.x. 7689 without knowing its id value. So you have several ways to deal with it. One of them is to iterate over them using for...in loop:
for(var cakeId in response.cakes){
var cake = response.cakes[cakeId];
console.log(cake);
// Do whatever you want with your cake
}
I am sorry if I misunderstood you. If so, please clarify the question by providing us with some examples of what you would like to achieve.
create a function
function getCake(obj,key){
let cake = obj['cakes'][key];
return cake;
}
call
let cakes = {
"status": true,
"cakes": {
"7689": {
"id": 7689,
"flavor": "chocolate",
"cookDetails": {
"id": 101,
"firstName": "Name1",
"lastName": "LastName1"
}
},
"7690": {
"id": 7690,
"flavor": "vanilla",
"cookDetails": {
"id": 102,
"firstName": "Name2",
"lastName": "LastName2"
}
}
}
}
getCake(cakes,'7689');
Try this out
const cakesObject = {
"status": true,
"cakes": {
"7689": {
"id": 7689,
"flavor": "chocolate",
"cookDetails": {
"id": 101,
"firstName": "Name1",
"lastName": "LastName1"
}
},
"7690": {
"id": 7690,
"flavor": "vanilla",
"cookDetails": {
"id": 102,
"firstName": "Name2",
"lastName": "LastName2"
}
}
}
};
// this is required only if cakesObject is strigified
const { cakes } = JSON.parse(cakesObject);
const cakesArray = [..Object.values(cakes)];
cakesArray.forEach(cake => {
const { id } = cake;
// write further logic
})
I am currently working on a REST API / website project, where my REST API has to return an array of objects from the server, via a response and using GSON to make a Json array out of the data. However, when trying to get values from the javascript array for the website, I keep getting undefined. This is the array:
var userArr =[
{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [
{
"id": 1,
"name": "Fodbold",
"people": [
"0x1"
]
}
],
"id": 1,
"address": {
"id": 1,
"street": "Street1",
"cityInfo": {
"id": 1,
"zipCode": "0555",
"city": "Scanning"
},
"infoList": [
"0x1",
"0x2"
]
},
"phones": [
{
"id": 1,
"number": "123124",
"info": "0x1"
}
]
}
];
When I try to call userArr[0].firstName, I get an error saying that it's undefined, even though the data is there. This is from a get call, which I am doing in my javascript from my REST API, which sends back this specific array. I have tried looping through the array, with multiple objects inside, however I am unable to retrieve any info at all.
Your userArr is an array of objects which do not have firstName property. They have only one property named 0x1 for some reason. And this 0x1 property has firstName property.
You can access firstName of 0x1 property using this notation:
userArr[0]["0x1"].firstName
Here is the working demo:
var userArr = [{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [{
"id": 1,
"name": "Fodbold",
"people": [
"0x1"
]
}],
"id": 1,
"address": {
"id": 1,
"street": "Street1",
"cityInfo": {
"id": 1,
"zipCode": "0555",
"city": "Scanning"
},
"infoList": [
"0x1",
"0x2"
]
},
"phones": [{
"id": 1,
"number": "123124",
"info": "0x1"
}]
}
}];
console.log(userArr[0]["0x1"].firstName);
By the way, there is a missing closing } bracket in the end of the array in your code.
I think if you write this code this way it is easy to understand and find the problem
var userArr =[
{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [{"id": 1,"name": "Fodbold","people": ["0x1"]}],
"id": 1,
"address": {"id": 1,"street": "Street1","cityInfo": {"id": 1,"zipCode": "0555","city": "Scanning"},
"infoList": ["0x1","0x2"]},
"phones": [{"id": 1,"number": "123124","info": "0x1"}]
}
}
];
You also missing the last second bracket.
Then you could use this console.log(userArr[0]["0x1"].firstName);
try this one
userArr[0]["0x1"].firstName
Incase value "0x1" is dynamic, you can access it by using Object.keys(userArr[0])[0] to get the first key of the object.
Here is solution:
var userArr = [{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [{
"id": 1,
"name": "Fodbold",
"people": [
"0x1"
]
}],
"id": 1,
"address": {
"id": 1,
"street": "Street1",
"cityInfo": {
"id": 1,
"zipCode": "0555",
"city": "Scanning"
},
"infoList": [
"0x1",
"0x2"
]
},
"phones": [{
"id": 1,
"number": "123124",
"info": "0x1"
}]
}
}];
console.log(userArr[0][Object.keys(userArr[0])[0]].firstName);
I have a list like this
{"ids": [
{
"id1": {
"name": "name1",
"lastname": "lastname1"
}
},
{
"id2": {
"name": "name2",
"lastname": "lastname2"
}
},
{
"id3": {
"name": "name3",
"lastname": "lastname3"
}
},
{
"id4": {
"name": "name4",
"lastname": "lastname4"
}
}
]
}
Then I retrieve and display it with this:
import {Component} from '#angular/core';
import {AngularFire, FirebaseListObservable} from 'angularfire2';
#Component({
selector: 'app',
templateUrl: `
<ul>
<li *ngFor="let id of ids | async">
{{ id.name }}
</li>
</ul>
`,
})
class AppComponent {
ids: FirebaseListObservable<any>;
constructor(af: AngularFire) {
this.ids = af.database.list('/ids');
}
}
The result:
name1
name2
name3
name4
Let's say I would like to reorder/move some objects, so I get result like this:
name3
name1
name2
name4
What would be a good way to structure my objects to easily achieve this?
I could add "order" property, update it and order the query by "order" property.
this.ids = af.database.list('/ids',{
query: {
orderByChild: 'order'
}
});
Or maybe I could add previous id key as a property, but how to display the list then, taking "previous" property into consideration? I figure out how to achieve this to avoid future scalability issues.
First, you will have to add property for storing order.
Second, you should not be saving this data as array as firebase stores it as object anyway. Instead you should be saving as object.
Check out the following link for more info.
https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html
So, your firebase database should look this.
"ids": {
"id1": {
"name": "name1",
"lastname": "lastname1",
"order": 1
},
"id2": {
"name": "name2",
"lastname": "lastname2",
"order": 2
},
"id3": {
"name": "name3",
"lastname": "lastname3",
"order": 3
},
"id4": {
"name": "name4",
"lastname": "lastname4",
"order": 4
}
}
And you should be querying by order property.