我有一些要提取的 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/