如何映射嵌套对象的数组



我有一个名为company的数组,它在mongo DB中保存了多个名为details的对象,我需要从中获取数据,特别是,我想从company array中获取company nameemployee's names,并将它们显示在list中。我的问题是如何在数组中进行钻取并呈现companyemployee names

当前在List component中的嵌套映射中,当我执行details.employee时,我只能从company ABC获得person1的结果,并且我需要从company ABCcompany EFG中显示的所有结果person 1, 2, and 3";

以下是来自sandbox的代码(请注意,只需查看List.js(

import axios from "axios";
import { useEffect, useState } from "react";
const List = () => {
const [company, setCompany] = useState([
{
details: [
{
employee: "person2",
date: "test date",
tax: "test tax",
balance: "22"
},
{
employee: "person3",
date: "test date",
tax: "test tax",
balance: "22"
}
],
company: "TEST-ABC",
_id: "60dba9fe7641a44d40364c1f",
__v: 0
},
{
details: {
employee: "person1",
date: "test date",
tax: "test tax",
balance: "22"
},
company: "TEST-EFG",
_id: "60dba9fe7641a44d40364c1f",
__v: 0
}
]);
return (
<>
<h2>Customer List</h2>
{company.map((c, i) => (
<ul key={i}>
{c.company}
{company.map((d, i) => (
<li key={i}>{d.details.employee}</li>
))}
</ul>
))}
</>
);
};
export default List;

return (
<>
<h2>Customer List</h2>
{company.map((c, i) => (
<li key={i}>
{c.company}
{company.map((d, i) => (
<li key={i}>{d.details.employee}</li>
))}
</li>
))}
</>
);
};
export default List;

内部循环需要覆盖员工,而不是再次覆盖company

考虑将有状态变量设为复数,这样也更容易理解。(由于在映射时需要引用单个公司,因此不希望整个公司阵列也被命名为company(

输入结构很奇怪,detail看起来要么是数组,要么是对象。(如果可能的话,请将结构更改为一致,使其始终为数组。否则,每次渲染时都必须检查它是数组还是对象。(

现场演示:

const App = () => {
const [companies, setCompanies] = React.useState([
{
details: [
{
employee: "person2",
date: "test date",
tax: "test tax",
balance: "22"
},
{
employee: "person3",
date: "test date",
tax: "test tax",
balance: "22"
}
],
company: "TEST-ABC",
_id: "60dba9fe7641a44d40364c1f",
__v: 0
},
{
details: {
employee: "person1",
date: "test date",
tax: "test tax",
balance: "22"
},
company: "TEST-EFG",
_id: "60dba9fe7641a44d40364c1f",
__v: 0
}
]);


return (
<React.Fragment>
<h2>Customer List</h2>
{companies.map((company, i) => (
<ul key={i}>
{company.company}
{
Array.isArray(company.details)
? company.details.map((detail, j) => <li key={j}>{detail.employee}</li>)
: company.details.employee
}
</ul>
))}
</React.Fragment>
);
};
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

相关内容

  • 没有找到相关文章

最新更新