[英]How can I loop through a nested array within an object?
So this is the JSON file with 3 objects所以这是包含 3 个对象的 JSON 文件
export const Projects = [
{
id: 1,
name: 'Site 1',
tech: [
'HTML',
'CSS',
'SASS',
'React'
],
description: 'Lorem1',
image: '/Image4.jpg'
},
{
id: 1,
name: 'Site 2',
tech: [
'HTML',
'CSS',
'SASS',
'React'
],
description: 'Lorem2',
image: '/Image4.jpg'
},
{
id: 1,
name: 'Site 3',
tech: [
'HTML',
'CSS',
'SASS',
'React'
],
description: 'Lorem3',
image: '/Image4.jpg'
}
];
I am trying to loop through the 'tech' arrays and return each item on its own.我正在尝试遍历“技术” arrays 并自行返回每个项目。 When I loop through them, right now I only get the full array and I can only put them all into a single div.
当我遍历它们时,现在我只能得到完整的数组,我只能将它们全部放入一个 div 中。 This is how currently I do it and it works fine with the other parts, however, how can I receive the "tech" part with individual objects, rather than just the one array?
这就是我目前的做法,并且它与其他部分一起工作得很好,但是,我怎样才能接收带有单个对象的“技术”部分,而不仅仅是一个数组?
const Portfolio = () => {
const portfolioItem = Projects.map((project, i) => {
return <Item
key={i}
image={Projects[i].image}
description={Projects[i].description}
name={Projects[i].name}
tech={Projects[i].tech}
/>
})
You can use Array.flatMap()
to iterate the projects, with an internal Array.map()
to iterate the tech.您可以使用
Array.flatMap()
来迭代项目,使用内部Array.map()
来迭代技术。
Note: The project.id
should be unique and used with the tech
as the key for the item.注意:
project.id
应该是唯一的,并与tech
一起用作项目的键。
const Portfolio = () => {
const portfolioItem = Projects.flatMap(project =>
project.tech.map(tech => (
<Item
key={`${project.id}-${tech}`}
image={project.image}
description={project.description}
name={project.name}
tech={tech}
/>
)
Assuming that rendering of tech
prop is implemented in a simple way, like this:假设
tech
prop 的渲染以简单的方式实现,如下所示:
const Item = ({tech}) => <div>{tech}</div>
Then you can map the array of strings into an array of React elements:然后你可以将 map 字符串数组转换成 React 元素数组:
<Item
key={i}
image={Projects[i].image}
description={Projects[i].description}
name={Projects[i].name}
tech={Projects[i].tech.map((t) => <span>{t}</span>)}
/>
Alternatively, you can convert the array to a single string, with explicit separator:或者,您可以将数组转换为单个字符串,并使用显式分隔符:
tech={Projects[i].tech.join(', ')}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.