【发布时间】:2023-04-08 16:28:01
【问题描述】:
我正在尝试从对象数组中选择一个值,而这些值只能来自第一个对象。 首先我有一个这样的对象数组:
items [
[
{id: 1, title: "title1", imgUrl: "https://someimage1"},
{id: 2, title: "title2", imgUrl: "https://someimage2"}
],
[
{id: 1, title: "title1", imgUrl: "https://someimage1"},
{id: 2, title: "title2", imgUrl: "https://someimage2"}
],
[
{id: 1, title: "title1", imgUrl: "https://someimage1"},
{id: 2, title: "title2", imgUrl: "https://someimage2"}
]
]
我打算在页面上显示标题和img url。我正在使用反应,这是我迄今为止尝试过的:
items.map(item => {
//here i enter each array of the big array individually
//here i will enter first object of the give array
console.log('ITEM:', item[0])
})
在 console.log 我得到这个:
ITEM: {id: 1, title: "title1", imgUrl: "https://someimage1"}
ITEM: {id: 1, title: "title1", imgUrl: "https://someimage1"}
ITEM: {id: 1, title: "title1", imgUrl: "https://someimage1"}
但我需要得到每个title 和imgUrl 所以在我的.map() 中我这样做:
items.map(item => {
//here i enter each array of the big array individually
//here i will enter first object of the give array
console.log('ITEM:', item[0].title)
})
但我收到此错误:
TypeError: 无法读取未定义的属性“标题”
我不明白为什么我认为我可以使用点符号来访问对象中您想要的任何键:
for more context:
<div>
{
items.map((item) => {
return <ul>
<li>
<div>
<p>{item[0].title}</p>
<img src={item[0].url}/>
</div>
</li>
</ul>
})
}
</div>
我对上述问题的解决方案
所以我花了一些时间来解决这个问题,这对我有用:
items.map((item) => {
return item.map ((x, index) => {
if (index === 0) {
return <ul>
<li>
<div>
<p>{ x.title }</p>
<img src={x.url}/>
</div>
</li>
</ul>
}
})
})
仍然不确定为什么我最初的想法 item[0].title 在没有嵌套 map() 函数的情况下无法工作
【问题讨论】:
-
您在第一个代码示例中的“对象数组”不是有效的语法,并且看起来如果它是 有效的语法,它将是一个数组数组。您可能需要查看/修改它,否则将很难理解您正在处理的条件......
-
请为您的问题创建一个可重现的代码 sn-p(通过单击
[<>]按钮)。根据您提供的详细信息,我无法重现您的错误 -
另外,在你的最后一段代码中
item[0].url应该是item[0].imgUrl。我也很确定在编写多行代码时需要将 JSX 括在括号中。 -
我在下面的答案中添加了更新,以响应您对问题的更新以及您的解决方案。在这种情况下,我认为您不应该嵌套循环(此外,您在所有回调迭代中使用
.map()而不返回值被认为是反模式,我提供了替代方案)。干杯!
标签: javascript reactjs