简体   繁体   English

映射对象数组并访问 object 值

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

I am trying to pick a value from array of object and the values can only be from first object.我正在尝试从 object 数组中选择一个值,并且这些值只能来自第一个 object。 Firstly i have a array of objects like this:首先我有一个这样的对象数组:

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"}
  ]
]

I am planning to display the title and img url on the page.我打算在页面上显示标题和img url。 I am using react and this is what i have tried so far:我正在使用反应,这是我迄今为止尝试过的:

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])
})

in console.log i get this:在 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"}

but I need to get each title and imgUrl so in my .map() I do this:但我需要获取每个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)
    })

but I get this error:但我收到此错误:

TypeError: Cannot read property 'title' of undefined TypeError:无法读取未定义的属性“标题”

I don't understand why I thought I would be able to use dot notation to access whatever key in the object you would like:我不明白为什么我认为我可以使用点符号来访问您想要的 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>

MY SOLUTION TO THE ABOVE PROBLEM我对上述问题的解决方案

SO i have spend some time messing around with this issue and this works for me:所以我花了一些时间来解决这个问题,这对我有用:

            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>
                    }
                })
            })

Still not sure why my initial idea item[0].title not work without having nested map() function仍然不确定为什么我最初的想法item[0].title在没有嵌套 map() function 的情况下不起作用

Try using quotes around the keys:尝试在键周围使用引号:

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

[Update Based on OP updating Post: [基于 OP 更新帖子的更新:

Since map builds a new array, using it when you aren't using the returned array is an anti-pattern;由于 map 构建了一个新数组,因此在不使用返回的数组时使用它是一种反模式; use forEach or for-of instead.使用 forEach 或 for-of 代替。 Signs you shouldn't be using map:您不应该使用 map 的迹象:
A) You're not using the array it returns, and/or A)您没有使用它返回的数组,和/或

B) You're not returning a value from the callback. B)您没有从回调中返回值。

Further reading on.map() via Mozilla 通过 Mozilla 进一步阅读 on.map()

Furthermore nesting 2 loops in such a way will force twice as many iterations as it will still run length times.此外,以这种方式嵌套 2 个循环将强制进行两倍的迭代次数,因为它仍然会运行长度时间。

If you need to access a sub element and know its index or key then use that value by:如果您需要访问子元素并知道它的索引或键,则通过以下方式使用该值:

array[index] or object.key and use a single map() (example in full snippet) array[index]object.key并使用单个map() (完整片段中的示例)

If you do actually need to loop over every element (due to some condition not expressed in your question) instead use:如果您确实需要遍历每个元素(由于您的问题中未表达的某些条件),请改用:

.find() ( single elements ) .find()单个元素

or .filter(elm => elm === 'someValue') ( multiple elements ).filter(elm => elm === 'someValue')多个元素

or .reduce() ( multiple elements ) with mutating elements as you go.reduce() (多个元素) 与你一样的变异元素 go

or even .forEach() ( multi elements ) with performing additional functions outside of array building (you will need to push to something like let loopArray = [] )甚至.forEach()多元素)在数组构建之外执行其他功能(您需要推送到let loopArray = []类的东西)

Continue Original Answer]继续原始答案]

Move the ul tag outside the map statement and change url to imgUrl.将 ul 标签移到 map 语句之外,并将 url 更改为 imgUrl。

Keep in mind if items is generated via async then you will also need to validate items before using map , something like:请记住,如果items是通过异步生成的,那么您还需要在使用map之前验证items ,例如:

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

Working Snippet (without async check):工作片段(没有异步检查):

 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