我有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
})
}
}
}
答案 0 :(得分:1)
请查看http://jsfiddle.net/es47k33o/
这里有很多错误:
sname: groups.[i].subgroups[j].subgroupname
bookname: groups[i].subgroups[j].books[k].bookname
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
})
}
}
}
&#13;
答案 1 :(得分:1)
试试这个JSFiddle sample并查看浏览器控制台日志。
首先,您的JSON
已损坏,每组中都缺少}
,这是有效的:
var groups = [{
"__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"
}
}]
}]
}];
除了@Stefan Dochow识别的代码中的其他问题之外,使用变量来识别具有嵌套循环的这种逻辑中的对象总是更好。以下是一个例子:
var apiListData = [];
for (var i = 0, totalGroups = groups.length; i < totalGroups; i++) {
var group = groups[i];
var subGroups = group.subgroups;
for (var j = 0, totalSubGroups = subGroups.length; j < totalSubGroups; j++) {
var subGroup = subGroups[j];
var books = subGroup.books;
for (var k = 0, totalBooks = books.length; k < totalBooks; k++) {
var book = books[k].bookname;
apiListData.push({
groupName: group.groupname,
subGroupName: subGroup.subgroupname,
bookName: book.name
});
}
}
}
console.log('apiListData', apiListData);