【问题标题】:React Native: How to get length of an array from an imported JSON file?React Native:如何从导入的 JSON 文件中获取数组的长度?
【发布时间】:2018-10-07 11:01:41
【问题描述】:

我想从导入的文件中获取 JSON 数组的长度,但它返回未定义。我可以从中访问任何元素。我猜问题是这里的“书”不是数组?

book.json:

[
  {
    "author" : "Bill",
    "total_chapters" : 14,
  },
  {
    "author" : "Chan",
    "total_chapters" : 29,
  },
:
]

App.js:

import * as books from './assets/book.json';

const author = books[60].author; //returns author
console.log('#books: ' + books.length); //undefined
console.log('books is ' + books.constructor); // Books is function Object() { [native code] }
console.log('books: ' + books); //books: [object Object]

【问题讨论】:

  • books 的日志是什么?
  • 书籍:[object Object]
  • console.log(JSON.stringify(books))?
  • 为了完整起见,您能否在问题中添加books.json 的结构?

标签: json react-native


【解决方案1】:

感谢@snjmhj 的提示。书籍是一个对象,可以通过这种方式获得长度:

Object.values(books).length

【讨论】:

    猜你喜欢
    • 2015-06-09
    • 2021-10-19
    • 1970-01-01
    • 2020-07-10
    • 2021-10-10
    • 1970-01-01
    • 2015-07-15
    • 1970-01-01
    • 2021-08-12
    相关资源
    最近更新 更多