angularjs将值附加到内部数组中
Posted
技术标签:
【中文标题】angularjs将值附加到内部数组中【英文标题】:angularjs append value into inside array 【发布时间】:2017-04-05 23:56:37 【问题描述】:我有以下格式的数组。我在每个章节数组中附加值时遇到问题。我需要添加像'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
【问题讨论】:
怎么加,贴代码 您只需要迭代并添加checked
属性。 Array.forEach
就足够了
【参考方案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));
【讨论】:
以上是关于angularjs将值附加到内部数组中的主要内容,如果未能解决你的问题,请参考以下文章
将值附加到数据数组并保存在 Userdefault swift