我試圖將vm.scholasticlist
轉換爲vm.parentList2
。 在vm.scholasticlist
,s_gid是獨一無二的密鑰,PARENT_ID指向父s_gid。將對象數組轉換爲父子關係
vm.scholasticlist是我從WebService獲取的返回值。 我正在嘗試以下JavaScript代碼,但無法構建它。
vm.scholasticlist = [];
vm.parentList = [];
vm.parentList2 = [];
for (var i in vm.scholasticlist) {
if(vm.scholasticlist[i]['parent_id'] == 0){
vm.parentList.push(vm.scholasticlist[i])
}
}
vm.parentList2 = vm.parentList;
for (var i in vm.parentList) {
console.log(vm.parentList[i]['s_gid'])
for (var x in vm.scholasticlist) {
if(vm.scholasticlist[x]['parent_id'] === vm.parentList[i]['s_gid']){
console.log(vm.parentList[i]['s_gid'])
vm.parentList2.push(vm.scholasticlist[x])
}
}
}
vm.scholasticlist = [{
"s_gid": "10",
"m_s_p_id": "1",
"subject_group_name": "Foundation of Information Technology",
"parent_id": "0",
"sname": ""
}, {
"s_gid": "11",
"m_s_p_id": "2",
"subject_group_name": "Life Skills",
"parent_id": "0",
"sname": ""
}, {
"s_gid": "15",
"m_s_p_id": "2",
"subject_group_name": "Thinking Skills",
"parent_id": "11",
"sname": "Th.sk"
}, {
"s_gid": "15",
"m_s_p_id": "2",
"subject_group_name": "Thinking Skills",
"parent_id": "11",
"sname": "Th.sk"
}]
希望建立新的JSON與父子關係
vm.parentList2 = [{
"s_gid": "10",
"m_s_p_id": "1",
"subject_group_name": "Foundation of Information Technology",
"parent_id": "0",
"sname": ""
}, {
"s_gid": "11",
"m_s_p_id": "2",
"subject_group_name": "Life Skills",
"parent_id": "0",
"sname": "",
"child": [{
"s_gid": "15",
"m_s_p_id": "2",
"subject_group_name": "Thinking Skills",
"parent_id": "11",
"sname": "Th.sk"
}, {
"s_gid": "15",
"m_s_p_id": "2",
"subject_group_name": "Thinking Skills",
"parent_id": "11",
"sname": "Th.sk"
}]
}]
我真的沒有看到任何JSON,它看起來像javascript給我? – adeneo
@ adeneo,是的,我正在嘗試基於第一個與父子關係與JAVASCRIPT構建新的JSON數組。第一個JSON數組是沒有父子的web服務的響應。 – fresher
@fresher:這不是JSON,它只是Javascript對象。 JSON是一個*字符串*,你有什麼是對象文字。 JSON的談話完全與你的問題無關。 –