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

时间:2016-01-30 22:46:03

标签: 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']);
    }
}

当我运行此代码时,我收到以下错误:

Uncaught TypeError: Cannot read property 'length' of undefined(…)

感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

在您要求current_user.activities.where(activity_type: :personal) 之前检查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']);
}

答案 1 :(得分:1)

在检查对象长度之前,您必须检查对象是否有get_context_data。变化

submeanings

if (data[i]['submeanings'].length >= 1)

此外,如果有多个子菜单,您需要单独的循环来提取子菜单,如下所示:

if (data[i]['submeanings'] && data[i]['submeanings'].length >= 1)

跟踪多个指数很困难,所以我建议改为使用if (data[i]['submeanings'] && data[i]['submeanings'].length >= 1) { for(var j = 0; j < data[i]['submeanings'].length; j++) { definitions.push(data[i]['submeanings'][j]['meaning']); } } https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

答案 2 :(得分:0)

这是因为您在JSON数据的第二个对象中没有属性submeanings,因此您应该使用 hasOwnProperty() 检查对象是否具有属性得到它:

if (data[i].hasOwnProperty('submeanings')) {
    definitions.push(data[i]['submeanings'][i]['meaning']);
}

希望这有帮助。