如何访问另一个 JSON 对象数组中的 JSON 对象数组的第一个元素?

时间:2021-07-08 19:51:11

标签: javascript arrays json reactjs.net

我有一个反应组件。它得到一个 Head~3 数组。

json

在阅读了这些 StackOverflow 问题 How to access first element of JSON object arrayAccess first element of json array(还有很多)之后,我制作了组件渲染功能:

[
    {
        "itemNumber": "11BRC",
        "itemDescription": "Flat head Phillips Wood screw C-Pak 2x1/4",
        "featured": false,
        "categoryName": "Screws",
        "price": 4.74444444,
        "qtyOnHand": 22409.00000,
        "images": [
            {
                "itemnmbr": "11BRC",
                "fileseq": 16384,
                "filename": "Oval Head Slotted Wood Screws.jpg",
                "imageData": "/9j/4Q4nRXhpZgAATU0AKgAAAAgADAEOAAIAAAAgAAAAngEPAAIAAAASAAAAvgEQAAIAAAAKAAAA0AESAAMAAAABAAEAAAEaAAUAAAABAAAA2gEbAAUAAAABAAAA4gEoAAMAAAABAAIAAAExAAIAAAAgAAAA6gEyAAIAAAAUAAABCgITAAMAAAABAAIAAIdpAAQAAAABAAABIIglAAQAAAABAAADBAAAAxggICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgAE5JS09OIENPUlBPUkFUSU9OAE5JS09OIEQxWAAALcbAAAAnEAAtxsAAACcQQWRvYmUgUGhvdG9zaG9wIENTNS4xIE1hY2ludG9zaAAyMDEyOjA0OjA1IDE0OjI1OjA2AAAAABmCmgAFAAAAAQAAAlKCnQAFAAAAAQAAAlqIIgADAAAAAQABAACQAAAHAAAABDAyMTCQAwACAAAAFAAAAmKQBAACAAAAFAAAAnaRAQAHAAAABAECAwCRAgAFAAAAAQAAAoqSBAAKAAAAAQAAApKSBQAFAAAAAQAAApqSBwADAAAAAQADAACSCgAFAAAAAQAAAqKShgAHAAAAMAAAAqqSkAACAAAAAzE3AACSkQACAAAAAzE3AACSkgACAAAAAzE3AACgAAAHAAAABDAxMDCgAQADAAAAAQABAACgAgAEAAAAAQAABzWgAwAEAAAAAQAABBqgBQAEAAAAAQAAAuSiFwADAAAAAQACAACjAAAHAAAAAQMAAACjAQAHAAAAAQEAAACjAgAHAAAACAAAAtoAAAAAAAAACgAABOIAAAAAAAAACjIwMTE6MDM6MTQgMTA6MTA6NTEAMjAxMTowMzoxNCAxMDoxMDo1MQAAAAAEAAAAAQAAAAAAAAAGAAAAAAAAAAoAAAAAAAAACgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAICAQEAAAAAAgABAAIAAAAEUjk4AAACAAcAAAAEMDEwMAAAAAAAAAABAAAAAQAAAAQCAAAAAAAAAAAAAAYBAwADAAAAAQAGAAABGgAFAAAAAQAAA2YBGwAFAAAAAQAAA24BKAADAAAAAQACAAACAQAEAAAAAQAAA3YCAgAEAAAAAQAACqkAAAAAAAAASAAAAAEAAABIAAAAAf/Y/+0ADEFkb2JlX0NNAAH/7gAOQWRvYmUAZIAAAAAB/
...

... 它说 render() { const items = this.state.itemList; return ( <table className="table table-striped table-bordered"> <thead> <tr> <th>Item Number</th> <th>Item Description</th> <th>Item Image</th> </tr> </thead> <tbody> {items && items.map (item => <tr key={item.itemNumber}> <td>{item.itemNumber}</td> <td>{item.itemDescription}</td> <td><img className="fit-picture" src={"data:image/png;base64," + item.images[0].imageData} id={item.itemNumber + "Img"} alt={item.itemNumber} /></td> </tr> )} </tbody> </table> ); } 是未定义的。我什至尝试过 item.images[0]Object.keys(item.images)[0].imageData,每个都有类似的错误消息。有人愿意指出我做错了什么吗?

1 个答案:

答案 0 :(得分:1)

itemList 中的某些条目可能没有图像,这会导致您看到的错误。为了说明这些条目,我们可以使用条件属性访问。

在渲染中尝试 item.images[0]?.imageData,这将在 images[0] 不存在时短路执行。

这个答案最初要求 JSON.parse(itemList),这是最高评论所指的内容。这不是 OP 遇到的问题。