I have a json object that I'm trying to map into a table within a react component. I'm having difficulty accessing the 'title' and the 'tooltip' from within the json object. The console log successfully shows me the entire the json object, but
this.props.selectedProducts.products.title
Which I thought would map to the 'title' part of the json data simply doesn't work. Can anyone tell me what I'm doing wrong & possibly how to correct it? Thanks in advance!
JSON:
selectedProducts: [
{
“start”: “Tue Jun 19 16:55:40 BST 2018”,
“products”: [
{
“title”: “SL Primary - Alaska (Westlaw PRO™)“,
“price”: “”
},
{
“title”: “SL Ninth Circuit Primary Law (Westlaw PRO™)“,
“price”: “”
}
]
}
],
React:
renderProducts() {
const selected = this.props.selectedProducts;
return this.props.selectedProducts.map((selected, i) => {
return (
<tr className="product-cells" key={i}>
<td> {selected.title} </td>
<td> {selected.price}</td>
</tr>
);
});
}
selectedProducts is an array, so you have to access the first object in the array, and map over products:
renderProducts() {
return this.props.selectedProducts[0].products.map((selected, i) => {
return (
<tr className="product-cells" key={i}>
<td> {selected.title} </td>
<td> {selected.price}</td>
</tr>
);
});
}
You should use first element of your selectedProducts array as answered before or use a second map if there will be more objects:
renderProducts() {
return (
this.props.selectedProducts.map(el =>
el.products.map(selected =>
<tr className="product-cells" key={selected.title}>
<td> {selected.title} </td>
<td> {selected.price}</td>
</tr>)
)
)
}
Do not use indexes as your keys. There could be some problems if you do so.
Related
I was working on this json data with react-table, it displays yet horizontally in a single <td></td>, your inputs are highly appreciated.
export const COLUMNS = [
{
Header: 'mId',
accessor: (row) => {return row.skus.map(sku => sku.mId); }
}]
Please note that I can access the data and print but it looks weird.
Expected Output:
<td>sku2620222 </td>
<td>sku2620220</td>
<td>sku2680407 </td>
<td>sku2680408 </td>
<td>sku10980349 </td>
<td>sku2680406</td>
Real output:
<td> sku2620222sku2620220sku2680407sku2680408sku2680405sku10980349sku2680406</td>
Basically I want it to display in every row. Thanks a lot
Each item you map through needs to be in its own row. Then you can add as many table downs as you need. That way each time you map through it, it will render a new table row. Here is an extremely simple table you can follow.
export default function App() {
let data = [
{sku: "sku2620222"},
{sku: "sku2620220"},
{sku: "sku2680407"},
{sku: "sku2620222"},
{sku: "sku2680408"},
]
let tabledata = data.map(i => {
return (
<tr>
<td>
{i.sku}
</td>
</tr>
)
})
return (
<>
<table>
<thead>
<tr>
<th>
SKU
</th>
</tr>
</thead>
<tbody>
{tabledata}
</tbody>
</table>
</>
)
}
I have a JSON that is coming like this and I want to show this JSON in the table in React.
{
"Status": true,
"discounts": {
"individual": {
"number_of_cars_discount": {
"1": "1",
"10": "1",
"2": "0.98",
}
}
},
"main_price": {
"client_type": "individual",
"large_car": {
"100": "3",
"1000": "0.9",
"100000": "0.60",
},
}
}
So to do this, I defined
const [mainPrice, setMainPrice] = useState({});
in the parent component and I fetched it like this:
setMainPrice(res.data.main_price);
I sent the mainPrice to the child component where I want to display JSON in the table:
<tbody>
<tr>
<td>
{Object.keys(individualPosts).map((key) => (
<tr>
<td key={key}>{individualPosts[key]}</td>
</tr>
))}
</td>
<td>
{Object.keys(mainPrice.large_car).map((key) => (
<tr>
<td key={key}>{mainPrice.large_car[key]}</td>
</tr>
))}
</td>
</tr>
</tbody>
But it gives me an error: TypeError: Cannot convert undefined or null to object
But I couldnt figure out why.
I have other types of cars like large_cars, small_cars so I need to take the mainPrice like this. I don't want to define all the types of cars and send them to the child component as a props. Or should I make it like this?
Please give me advice and the solution.
Null check required in such cases to avoid errors.
Try this
<td>
{Object.keys(mainPrice?.large_car).length > 0 && Object.keys(mainPrice?.large_car).map((key) => (
<tr>
<td key={key}>{mainPrice.large_car[key]}</td>
</tr>
))}
</td>
In my project I getting the data from JSONPlaceholder - Users
I'm new in Angular, so if you find something stupid in the way I get the data please warn me.
dataFromServer;
constructor(private http: HttpClient){
this.dummyPromise.then(
response => {
console.log("response from dummy promise:", response);
this.dataFromServer = response;
},
error => {
console.log("Error happened with dummy promise:", error)
}
)
}
dummyPromise = new Promise((resolve, reject) => {
this.http.get('https://jsonplaceholder.typicode.com/users').subscribe(data => {
console.log(data);
this.dataFromServer = data;
});
//resolve(returnData);
});
Problem is, in my HTML file, I write the data into a table like this:
<tr *ngIf="dataFromServer">
<td>{{dataFromServer[0].id}}</td>
<td>{{dataFromServer[0].name}}</td>
<td>{{dataFromServer[0].username}}</td>
<td>{{dataFromServer[0].email}}</td>
</tr>
<tr *ngIf="dataFromServer">
<td>{{dataFromServer[1].id}}</td>
<td>{{dataFromServer[1].name}}</td>
<td>{{dataFromServer[1].username}}</td>
<td>{{dataFromServer[1].email}}</td>
</tr>
... for all the 10 people. I want to do it dynamically, as many lines as many people's data I get.
I think that you should try to use *ngFor instead of *ngIf. I will give you an example.
<tr *ngFor="let data of dataFromServer">
<td>{{data.id}}</td>
<td>{{data.name}}</td>
<td>{{data.username}}</td>
<td>{{data.email}}</td>
</tr>
So, it will repeat for every object in your dataFromServer
use ngFor to iterate on an array of data:
<table *ngIf="dataFromServer">
<tr *ngFor="let item of dataFromServer">
<td>{{item.id}}</td>
...
</tr>
</table>
the ngIf condition on the table will prevent console errors/rendering issues if dataFromServer is null/undefined before receiving from your API
You can replace your html code as bellow
<tr *ngFor="let row of dataFromServer">
<td>{{row.id}}</td>
<td>{{row.name}}</td>
<td>{{row.username}}</td>
<td>{{row.email}}</td>
</tr>
You can use *ngFor to do it. It's pratically a for in the html. As an example we assume that we have a component like this :
private users: User[] = [];
ngOnInit(){
this.service.getUser()
.subscribe(userList => {
this.users = userList;
});
}
The User class :
export class User {
public id: number;
public name: string;
}
You can use the *ngFor in your html like this way :
<span *ngFor="let user of users">
UserID: {{user.id}} - User Name: {{user.name}}
</span>
So basically, related to your code, just put in an object of User the json data you get from the http call, then modify the html like this way :
<tr *ngFor="let user of users">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
.....
</tr>
I have the following firebase JSON object:
"items" : {
"111111111111" : {
"ins" : { <<<<<<<<< I want to display the length of this
"1523878813443" : true,
"1523878891312" : true,
"1523878911379" : true,
"1523879091312" : true
},
"name" : "10",
"outs" : { <<<<<<<<< and this one too
"1523878813443" : true,
"1523878891312" : true,
"1523878911379" : true
},
"ownerID" : "QpMHsVHHRrMvk92rbSQvcYEv4en1"
}
}
Here is the template part on where I am trying to get these values to update:
<tbody>
<tr v-for="item in items" >
<td>
{{item.childone - door.childtwo}}
</td>
<td>
{{item.childone}}
</td>
<td>
{{item.childtwo}}
</td>
</tr>
</tbody>
I got it to display the JSON object like this:
The "In's" column should display 4, the "Out's" should display 3 and the "Balance" column should display 1.
This is the firebase setup and data code on my component:
import firebase { doorsRef } from '../firebase-config';
export default {
firebase() {
return {
items: itemsRef,
}
},
...etc
}
Any kind soul out there who would be willing to help?
Knowing that a JSON object has keys (and values) I have used this on my template instead:
{{Object.keys(JSON.Object).length}}
So in my case this did the trick:
<tbody>
<tr v-for="item in items" >
<td>
{{Object.keys(item.childone).length - Object.keys(item.childtwo).length}}
</td>
<td>
{{Object.keys(item.childone).length}}
</td>
<td>
{{Object.keys(item.childtwo).length}}
</td>
</tr>
</tbody>
Alternative you you can also count the number of values: {{Object.values(JSON.Object).length}}
I would like to get help and guide on how can i manipulate text/string that being called from MS-SQL Database. So here is my SettingController.cs partial code for index viewing:
public ActionResult Index()
{
var datacontext = new SGM_SIDDataContext();
var dataToView = from m in datacontext.SGMs
orderby m.Seq
select m;
return View(dataToView.ToList());
}
And This is my index.cshtml codes:
#model IEnumerable<MVC_Apps.Models.SGM>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
SID
</th>
<th>
Abbrev
</th>
<th>
Val
</th>
<th>
Seq
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.SID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Abbrev)
</td>
<td>
#Html.DisplayFor(modelItem => item.Val)
</td>
<td>
#Html.DisplayFor(modelItem => item.Seq)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.GID })
</td>
</tr>
}
</table>
So roughly I got a View. Now here is what i would like to do:
1) The data 'item.Val' on Index.cshtml view will be like this:
A,L,C,H
and sort of like that. But the might be line where the data only contain:
H or C or none(Null value)
But if the data contain more than one char like say it does set for K and L, the data in item.Val will look like this:
A,L
Which the data being separate by comma. So now i want to split that item.Val data and do if statement on it. Where I would like to check every data in item.Val if it contain K or L or C or H or all of them or none of them(Sorry if my english is bad). And I would like to view it as , if all the data contain H so in table view, the will be column named Hotel while if the data also have L so another column of Lounge will be display with a check button being checked.
the possible char in item.Val is:
A = Admin
L = Lounge
H = Hotel
C = Customer
Any help and ideas much appreciated. Thank you in advanced.
Update information:
Thanks Im starting to get what is it. What i really want to do is, when the item.Val does contain H(which is for hotel) then the view will have table column with header name Hotel and at the record it will have tick checkbox.
This is sample picture of table view: http://imagebin.org/152941
But then the Hotel, Admin and User information either it is tick or not is in item.Val
For example for Smith, the item.Val data look like this : C,
For example for Anna , the item.Val data look like this : H,C,
P.S : - the var conf line is a test code. Ignore it as I already delete it from my source. :)
Create a ViewModel similar to
public class MyViewModel
{
// items from your model
public int Id{get;get;}
public String Vals{get;set;} // A,L,C,H
...
...
public bool IsHotel
{
get
{
return Vals.Split(',').Contains("H");
}
}
public bool IsAdmin
{
get
{
return Vals.Split(',').Contains("A");
}
}
public bool IsCust
{
get
{
return Vals.Split(',').Contains("C");
}
}
}
In the controller action
public ActionResult Index()
{
var datacontext = new SGM_SIDDataContext();
var dataToView = from m in datacontext.SGMs
orderby m.Seq
select new MyViewModel()
{
// items from your datacontext
Id= m.SID,
//etc...
};
var conf = from m in datacontext.SGMs // what's the purpose of this query??
select m.Val;
return View(dataToView.ToList());
}
The View will need to be updated, so include columns for Hotel, Cust, Admin and any others you need. I would suggest that you keep it simple and don't try to create the HTML columns on the fly. If you want to do this, you probably will need to inspect all Vals in every object of your list first to determine what columns are needed. In the view
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.SID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Abbrev)
</td>
<td>
#(item.IsHotel? "Checked" : "")
</td>
<td>
#(item.IsAdmin? "Checked" : "")
</td>
<td>
#(item.IsCust? "Checked" : "")
</td>
<td>
#Html.DisplayFor(modelItem => item.Seq)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.GID })
</td>
</tr>
}