Hi im newbie on react js,
how to call nested object(array/list) on main object, i mean object in object
<tbody>
{
vehicles.map((v, index) =>(
<tr key={v.id}>
<td>{index 1}</td>
<td>{v.type}</td>
<td>{v.plateNumber}</td>
{v.employee.map(item => {
return (
<td>
<ul>{item.name}</ul>
</td>
);
})}
<td>
<Link className="btn btn-info" to={`/vehicles/edit/${v.id}`}>Update</Link>
<button className="btn btn-danger ml-2" onClick={() => {deleteSweetAlert(v.id)}}>Delete</button>
</td>
</tr>
))
}
</tbody>
This one my JSON example
[
{
"id": 1,
"type": "MasterCard",
"plateNumber": "3747948",
"status": "1",
"employee": {
"id": 1,
"name": "Joanne Hagenes Sr.",
"location": "60794 Rippin Cove Suite 080\nTroyberg, ND 95778",
"department": "Wuckert-Luettgen",
"status": "1"
}
}
]
I always get this error message at the console
react-dom.development.js:26874 Uncaught TypeError: v.employee.map is not a function
CodePudding user response:
map()
function can only applied with an array, so in your case employee
should be an array instead an object:
{
"id": 1,
"type": "MasterCard",
"plateNumber": "3747948",
"status": "1",
"employee": [{
"id": 1,
"name": "Joanne Hagenes Sr.",
"location": "60794 Rippin Cove Suite 080\nTroyberg, ND 95778",
"department": "Wuckert-Luettgen",
"status": "1"
}]
}
Another way to fix this, since each of your vehicle
contains only 1 employee
(based on how u named it). So i suppose you dont need to use map()
function in this case:
<tbody>
{
vehicles.map((v, index) =>(
<tr key={v.id}>
<td>{index 1}</td>
<td>{v.type}</td>
<td>{v.plateNumber}</td>
<td>
<ul>{item.name}</ul>
</td>
<td>
<Link className="btn btn-info" to={`/vehicles/edit/${v.id}`}>Update</Link>
<button className="btn btn-danger ml-2" onClick={() => {deleteSweetAlert(v.id)}}>Delete</button>
</td>
</tr>
))
}
</tbody>
CodePudding user response:
You can use interface to define.
interface IFoo {
foo: string;
}
interface IBaz {
baz: string;
foo: IFoo;
}
const obj: IBaz = {
baz: 'bar',
foo: {
foo: 'foo',
},
};
console.log(obj.baz); // -> baz
console.log(obj.foo.foo); // -> foo