我的json文件看起来像这样:
{
"results": {
"name1": {
"printouts": {
"property1": [{
"someName": "someText",
"someName2": "someURL",
"someName3": integer,
"someName4": boolean
}
],
"property2": [
"someText"
],
"property3": [
"someText"
],
"property4": [
"someText"
],
"property5": [
"someText"
],
"property6": [
"someText"
]
},
"someName": "someText",
"someName2": "someURL",
"someName3": integer,
"someName4": boolean
},
"name2": {
"printouts": {
"property1": [{
"fulltext": "someText",
"fullurl": "someURL",
"namespace": integer,
"exists": boolean
}
],
"property2": [
"someText"
],
"property3": [
"someText"
],
"property4": [
"someText"
],
"property5": [
"someText"
],
"property6": [
"someText"
]
},
"someName": "someText",
"someName2": "someURL",
"someName3": integer,
"someName4": boolean
},
......
}
我想要的是访问property6
中每个对象的printouts
。
到目前为止我做了什么:
for (i in results) {
if (someOtherArray.length < 1) {
someOtherArray.push(i.printouts.property6.toString());
}
但这会让我错误:无法读取未定义的属性property6。我做错了什么?
任何想法?感谢。
答案 0 :(得分:2)
基本上,您使用
错误地访问了该属性i.printouts.property6
它必须是一个带有property accessor的对象,并带有变量的括号表示法。
data.results[i].printouts.property6
//^^^^^^^^^^^^^
然后你可以迭代键并选择你想要的属性。
var data = { results: { name1: { printouts: { property1: [{ someName: "someText", someName2: "someURL", someName3: 33, someName4: false }], property2: ["someText"], property3: ["someText"], property4: ["someText"], property5: ["someText"], property6: ["someText"] }, someName: "someText", someName2: "someURL", someName3: 37, someName4: true }, name2: { printouts: { property1: [{ fulltext: "someText", fullurl: "someURL", namespace: 35, "exists": true }], property2: ["someText"], property3: ["someText"], property4: ["someText"], property5: ["someText"], property6: ["someText"] }, someName: "someText", someName2: "someURL", someName3: 34, someName4: false } } };
Object.keys(data.results).forEach(function (k) {
console.log(data.results[k].printouts.property6);
});