【问题标题】:mapping through array of objects and accessing object values通过对象数组映射并访问对象值
【发布时间】: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"}

但我需要得到每个titleimgUrl 所以在我的.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(通过单击 [&lt;&gt;] 按钮)。根据您提供的详细信息,我无法重现您的错误
  • 另外,在你的最后一段代码中item[0].url 应该是item[0].imgUrl。我也很确定在编写多行代码时需要将 JSX 括在括号中。
  • 我在下面的答案中添加了更新,以响应您对问题的更新以及您的解决方案。在这种情况下,我认为您不应该嵌套循环(此外,您在所有回调迭代中使用 .map() 而不返回值被认为是反模式,我提供了替代方案)。干杯!

标签: javascript reactjs


【解决方案1】:

尝试在键周围使用引号:

items [
  [
    {"id": 1, "title": "title1", "imgUrl": "https://someimage1"},
    {"id": 2, "title": "title2", "imgUrl": "https://someimage2"}
  ]
]

【讨论】:

    【解决方案2】:

    [更新基于 OP 更新帖子:

    由于 map 构建了一个新数组,当你不使用返回的数组时使用它是一种反模式;使用 forEach 或 for-of 代替。 不应该使用地图的标志:
    A)你没有使用它的数组 返回,和/或

    B) 您没有从回调中返回值。

    Further reading on .map() via Mozilla

    此外,以这种方式嵌套 2 个循环将强制进行两倍的迭代次数,因为它仍然会运行长度时间。

    如果您需要访问子元素并知道它的索引或键,然后使用该值:

    array[index]object.key 并使用单个 map()(完整的 sn-p 示例)

    如果您确实需要遍历每个元素(由于您的问题中未表达的某些条件),请改用:

    .find()单个元素

    .filter(elm =&gt; elm === 'someValue')多个元素

    .reduce()多个元素)随你变化的元素

    甚至.forEach()多元素)在数组构建之外执行其他功能(您需要推送到let loopArray = []之类的东西)

    继续原始答案]

    将ul标签移到map语句外,将url改为imgUrl。

    请记住,如果items 是通过异步生成的,那么您还需要在使用map 之前验证items,例如:

    {(items && items.length) && items.map(item=>{
        /*code*/
    )}
    

    工作片段(没有异步检查):

    const SomeComponent = () => {
        const items = [
            [
                {id: 1, title: "title1.1", imgUrl: "https://p7.hiclipart.com/preview/917/362/567/halloween-trick-or-treating-double-ninth-festival-illustration-halloween-design-elements.jpg"},
                {id: 2, title: "title2", imgUrl: "https://someimage2"}
            ],
            [
                {id: 1, title: "title1.2", imgUrl: "https://image.shutterstock.com/image-vector/silhouette-cat-dog-on-white-600w-671156590.jpg"},
                {id: 2, title: "title2", imgUrl: "https://someimage2"}
            ],
            [
                {id: 1, title: "title1.3", imgUrl: "https://jngnposwzs-flywheel.netdna-ssl.com/wp-content/uploads/2019/05/Transparent-OrangeWhiteCat-768x1030.png"},
                {id: 2, title: "title2", imgUrl: "https://someimage2"}
            ]
        ];
        return (
            <div>
                    <ul>
                        {items.map((item,index) => {
                            return(
                                <li key={String(index)}>
                                    <div>
                                        <p>{item[0].title}</p>
                                        <img style={{width:'10%'}} src={item.imgUrl} alt={item.title}/>
                                    </div>
                                </li>
                            )
                        })}
                    </ul>
            </div>
        )
    }
    
    ReactDOM.render(
        <SomeComponent />,
        document.getElementById("react")
    );
    <div id='react'></div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

    【讨论】:

      猜你喜欢
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 2023-02-09
      相关资源
      最近更新 更多