簡體   English   中英

映射對象數組並訪問 object 值

[英]mapping through array of objects and accessing object values

我正在嘗試從 object 數組中選擇一個值,並且這些值只能來自第一個 object。 首先我有一個這樣的對象數組:

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:無法讀取未定義的屬性“標題”

我不明白為什么我認為我可以使用點符號來訪問您想要的 object 中的任何鍵:

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() function 的情況下不起作用

嘗試在鍵周圍使用引號:

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

[基於 OP 更新帖子的更新:

由於 map 構建了一個新數組,因此在不使用返回的數組時使用它是一種反模式; 使用 forEach 或 for-of 代替。 您不應該使用 map 的跡象:
A)您沒有使用它返回的數組,和/或

B)您沒有從回調中返回值。

通過 Mozilla 進一步閱讀 on.map()

此外,以這種方式嵌套 2 個循環將強制進行兩倍的迭代次數,因為它仍然會運行長度時間。

如果您需要訪問子元素並知道它的索引或鍵,則通過以下方式使用該值:

array[index]object.key並使用單個map() (完整片段中的示例)

如果您確實需要遍歷每個元素(由於您的問題中未表達的某些條件),請改用:

.find()單個元素

.filter(elm => elm === 'someValue')多個元素

.reduce() (多個元素) 與你一樣的變異元素 go

甚至.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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM