我有一个array of objects
如下:
[
{
"__v": 0,
"_id": "5634fa3df925a0ac02f1b0fa",
"groupname": "group 1",
"subgroups": [
{
"__v": 0,
"_id": "5634fa63f925a0ac02f1b0fc",
"subgroupname": "subgroup 1",
"books": [
{
"bookname": {
"name": "sasasasasasP"
}
}
]
]
},
{
"__v": 0,
"_id": "5634fa3df925a0ac02f1b0fd",
"groupname": "group 2",
"subgroups": [
{
"__v": 0,
"_id": "5634fa63f925a0ac02f1befc",
"subgroupname": "subgroup 2",
"books": [
{
"bookname": {
"name": "book 2"
}
}
]
]
}
]
我想从上面的对象在下面形成一个
array of objects
。[
{
"groupname": "Group 1",
"subgroupname": "subgroup 1",
"bookname": "Enersol"
},
{
"groupname": "Group 2",
"subgroupname": "subgroup 2",
"bookname": "Enersol"
}
]
以下是我尝试过的方法,但是在数组内形成第一个对象后,循环失败。
var apiListData = [];
for (var i = 0, len = groups.length; i < len; i++) {
for (var j = 0, len = groups[i].subgroups.length; j < len; j++) {
for (var k = 0, len = groups[i].subgroups[j].books.length; k < len; k++) {
apiListData.push({
gname: groups[i].groupname,
sname: groups.[i].subgroups[j].subgroupname,
bookname: groups[i].subgroups[j].books[k].bookname
})
}
}
}
最佳答案
请看看http://jsfiddle.net/es47k33o/
这里有很多错误:
您提供的JSON结构非常混乱,其固定在小提琴中
错字:sname: groups.[i].subgroups[j].subgroupname
中的点太多
要访问书名的字符串值,您必须比bookname: groups[i].subgroups[j].books[k].bookname
更深一层
您实际的算法问题是,您总是要重新声明变量len。我根据它们各自的索引重命名了第二个和第三个:
var apiListData = [];
for (var i = 0, len = groups.length; i < len; i++) {
for (var j = 0, lenj = groups[i].subgroups.length; j < lenj; j++) {
for (var k = 0, lenk = groups[i].subgroups[j].books.length; k < lenk; k++) {
apiListData.push({
gname: groups[i].groupname,
sname: groups[i].subgroups[j].subgroupname,
bookname: groups[i].subgroups[j].books[k].bookname.name
})
}
}
}
关于javascript - 嵌套循环未形成完整对象-问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33458008/