通过对象数组进行映射并访问对象值

时间:2019-10-20 23:51:05

标签: javascript reactjs

我正在尝试从对象数组中选择一个值,并且这些值只能来自第一个对象。 首先,我有一个这样的对象数组:

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。我正在使用react,这是到目前为止我尝试过的:

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:无法读取未定义的属性“ title”

我不明白为什么我认为我可以使用点表示法来访问您想要的对象中的任何键:

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()函数就无法工作

2 个答案:

答案 0 :(得分:0)

尝试在按键周围使用引号:

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

答案 1 :(得分:0)

[基于OP更新后的更新:

  

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

     

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

     

Further reading on .map() via Mozilla

此外,以这种方式嵌套2个循环将强制执行两倍的迭代,而迭代次数仍将是运行时间的两倍。

如果您需要访问子元素并知道其索引或键,请通过以下方式使用该值:

array[index]object.key并使用一个map()(完整代码段示例)

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

.find()单个元素

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

.reduce()多个元素),并且随需添加可变元素

甚至是.forEach()多个元素),它们在数组构建之外还具有执行其他功能的功能(您将需要使用let loopArray = []之类的东西)

继续原始答案]

将ul标签移到map语句之外,然后将网址更改为imgUrl。

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

{(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>

相关问题