简体   繁体   English

无法访问数组内 json 对象的属性

[英]cannot access properties of json objects inside array

I have an array of objects like我有一个对象数组,比如

[
   {
      "id":17368,
      "creationDate":1566802693000,
      "status":"InProgress",
      "type":"NEW",
      "agentType":"Master"
   },
   {
      "id":17368,
      "creationDate":1566802693000,
      "status":"InProgress",
      "type":"NEW",
      "agentType":"Master"
   },
   {
      "id":17368,
      "creationDate":1566802693000,
      "status":"InProgress",
      "type":"NEW",
      "agentType":"Master"
   },
   {
      "id":17368,
      "creationDate":1566802693000,
      "status":"InProgress",
      "type":"NEW",
      "agentType":"Master"
   }
]

But when trying to access the object property 'id' using console.log(array[0].id) throws a "cannot read property id of undefined error"但是,当尝试使用console.log(array[0].id)访问 object 属性“id”时,会抛出“无法读取未定义错误的属性 id”

However just logging the first object with console.log(array[0]) prints the object successfully.但是,只需使用console.log(array[0])记录第一个 object 即可成功打印 object。

{id: 17368, creationDate: 1566802693000, …}

Also printing the list of ids using array.map(x => console.log(x.id)) prints the list of ids successfully.使用array.map(x => console.log(x.id))打印 id 列表也会成功打印 id 列表。

I am in a situation where i need to access the first few specifically.我处于需要专门访问前几个的情况。 Where am i going wrong?我哪里错了?

try this console.log(array[0] && array[0].id)试试这个console.log(array[0] && array[0].id)

or you can use get from lodash-es like this:或者你可以像这样使用从 lodash-es 获取:

 import { get } from 'lodash-es'

const id=get(array[0], 'id', '')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM