javascript - 使用循环索引从对象中提取数据的问题

标签 javascript json

我有一些要提取的 JSON 数据。

我正在尝试提取一些数据并将其重新格式化为一个数组。我正在遍历数据,但在提取嵌套的 submeaning 对象中的数据时遇到问题。

JSON 数据:

var data = [
  {
    "meaning": "a procedure intended to establish the quality, performance, or reliability of something, especially before it is taken into widespread use.",
    "examples": [
      "no sparking was visible during the tests"
    ],
    "submeanings": [
      {
        "meaning": "a short written or spoken examination of a person's proficiency or knowledge.",
        "examples": [
          "a spelling test"
        ]
      },
      {
        "meaning": "an event or situation that reveals the strength or quality of someone or something by putting them under strain.",
        "examples": [
          "this is the first serious test of the peace agreement"
        ]
      },
      {
        "meaning": "an examination of part of the body or a body fluid for medical purposes, especially by means of a chemical or mechanical procedure rather than simple inspection.",
        "examples": [
          "a test for HIV",
          "eye tests"
        ]
      },
      {
        "meaning": "a procedure employed to identify a substance or to reveal the presence or absence of a constituent within a substance."
      }
    ]
  },
  {
    "meaning": "a movable hearth in a reverberating furnace, used for separating gold or silver from lead."
  }
]

算法:

// array to hold definitions
var definitions = [];

for (var i = 0; i < data.length; i++) {
    // push first 
    definitions.push(data[i]['meaning']);

    // push second, if submeaning data exists
    if (data[i]['submeanings'].length >= 1) {
        definitions.push(data[i]['submeanings'][i]['meaning']);
    }
}

当我运行这段代码时,出现以下错误:

未捕获的类型错误:无法读取未定义的属性“长度”(…)

感谢任何帮助。

最佳答案

在询问它的长度之前检查 submeanings 是否存在。

// push second, if submeaning data exists
if (data[i] && data[i]['submeanings'] && data[i]['submeanings'].length >= 1) {
    definitions.push(data[i]['submeanings'][i]['meaning']);
}

关于javascript - 使用循环索引从对象中提取数据的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35108143/

相关文章:

javascript - 日期选择器不工作(ASP.NET MVC)

javascript - Fancybox - 根据 id 从元素获取 html?

javascript - JavaScript 中的 Assets - Symfony2

java - 客户端发送的请求在语法上使用@DateTimeFormat 是不正确的

javascript - 为 JSON 创建嵌套对象

javascript - 所有人共享的First Load JS在next.js中相当重

javascript - 当我只想更改一个 id 时,多个 id 会受到影响(javascript 和 jquery)

javascript - 无法在 React 中访问嵌套的 JSON 对象

javascript - 删除 JSON 对象数组的第一个元素

json - 如何使用 serde_json 将 "NaN"反序列化为 `nan`?