我有以下格式的数组。我有问题在每个章节数组中附加值。我需要添加像'checked:true'这样的字段。我需要以相同的格式获取数据。期望是,需要相同的格式,在章节数组中添加一个字段。
{
"Books": [
{
"label":"Book1",
"data": [
{
"bookId": 3561,
"bookName": "AJ200",
"chapters": [
{
"id": 3926,
"name": "red"
},
{
"id": 3927,
"name": "yellow"
},
{
"id": 3928,
"name": "black"
}
]
}
]
},
{
"label":"Book2",
"data":[
{
"bookId": 3561,
"bookName": "AJ200",
"chapters": [
{
"id": 3564,
"name": "blue"
},
{
"id": 3565,
"name": "orange"
}
]
}
]
}
]
}
添加字段章节后,数组如下所示,
"chapters": [
{
"id": 3564,
"name": "blue",
"checked":true
},
{
"id": 3565,
"name": "orange"
"checked":true
}
答案 0 :(得分:1)
这有点冗长,但都是一样的!
var myObject =
{
"Books": [
{
"label":"Book1",
"data": [
{
"bookId": 3561,
"bookName": "AJ200",
"chapters": [
{
"id": 3926,
"name": "red"
},
{
"id": 3927,
"name": "yellow"
},
{
"id": 3928,
"name": "black"
}
]
}
]
},
{
"label":"Book2",
"data":[
{
"bookId": 3561,
"bookName": "AJ200",
"chapters": [
{
"id": 3564,
"name": "blue"
},
{
"id": 3565,
"name": "orange"
}
]
}
]
}
]
}
var books = myObject.Books;
for(var i=0; i<books.length; i++) {
var bookData = books[i].data;
for(var j=0;j<bookData.length;j++) {
var chapters = bookData[j].chapters;
for(var k=0;k<chapters.length;k++) {
chapters[k].checked = true;
}
}
}
console.log(JSON.stringify(books));