【发布时间】:2017-11-19 19:52:44
【问题描述】:
我通常习惯于使用 Object.keys() 函数。 但是这一次,对于以下 JSON 中的每个对象,我无法按名称读取属性的值:
JSON
var myData = {
"customNotes":{
"2017/04/17":{
"concernedDate":"April, 17, 2017",
"notesList":[
{
"id":25,
"title":"Note 25 Title"
},
{
"id":51,
"title":"Note 51 Title"
}
]
},
"2017/04/14":{
"concernedDate":"April, 14, 2017",
"notesList":[
{
"id":53,
"title":"Note 53 Title"
}
]
}
}
}
我需要的输出
我需要的是以下输出:
2017/04/17
concernedDate: April, 17, 2017
Number of notes: 2
Notes list:
- id: 25
- title: Note 25 Title
- id: 51
- title: Note 51 Title
- - - - - - - -
2017/04/14
concernedDate: April, 14, 2017
Number of notes: 1
Notes list:
- id: 53
- title: Note 53 Title
我的错误 JS 代码
$(Object.keys(myData.customNotes)).each(function(iGroup){
//Get Key/Val of each Group of notes
var keyGroup = Object.keys(myData.customNotes)[iGroup];
var valGroup = myData.customNotes[keyGroup];
//Print Key (the date as a string)
console.log(valGroup[0]);
//Print Key Property ('concernedDate')
console.log('concernedDate: ' + valGroup[0].concernedDate);
//Print Key Property Length ('notesList')
console.log('Number of notes: ' + valGroup[0].notesList.length);
//Print List of notes
console.log('Notes list:');
//If the property exists
if(valGroup[0].notesList){
//For each item in 'notesList'
$(Object.keys(valGroup[0].notesList)).each(function(iNote){
//Get Key/Val For each note
var keyNote = Object.keys(valGroup[0].notesList)[iNote];
var valNote = valGroup[0].notesList[keyNote];
//Print the properties of each note
console.log('- id: ' + valNote.id);
console.log('- title: ' + valNote.title);
});
}
});
【问题讨论】:
标签: arrays json for-loop foreach javascript-objects