[英]How can I loop through a Javascript object array assigning objects as children of other objects within? Tree/hierarchical structure
[英]How to dynamically generate javascript objects within other objects. Can you use a for loop inside an object?
我希望實現一組javascript對象,如下所示:
tabs[0]={
sections[0]={
title:"section0",
children[0]={
title:"Child0"
},
children[1]={
title:"Child1"
},
children[2]={
title:"Child2"
}
},
sections[1]={
title:"section1",
children[0]={
title:"Child0"
},
children[1]={
title:"Child1"
}
}
};
tabs[1]={
sections[0]={
title:"section0",
children[0]={
title:"Child0"
},
children[1]={
title:"Child1"
}
},
sections[1]={
title:"section1",
children[0]={
title:"Child0"
},
children[1]={
title:"Child1"
}
},
sections[2]={
title:"section2",
children[0]={
title:"Child0"
},
children[1]={
title:"Child1"
}
}
};
這是我的代碼,但是在Tab對象內的第一個for循環中出現“意外令牌”錯誤。 這是不允許的嗎? 我如何讀取這些數組並動態創建類似於上述對象的對象? 數組(以及隨后的對象)可以並且將隨着.csv文件的更改而更改,這就是為什么我需要動態創建這些對象的原因。 這些對象將與AngularJS的ng-repeat一起使用,以創建應用程序的選項卡式導航和側面導航。
this.tabData = tabsService.tabData;
var tabCount = tabsService.tabData.length;
var tabs={};
var tCounter = 0;
for (tCounter; tCounter<tabCount; tCounter++){
var tabURL = "Contents/Product Groups/"+this.tabData[tCounter]+"/sectionOrder.csv";
tabs[tCounter] ={
"TabSectionData" : $.getCsvArray(tabs[tCounter].tabURL), //gets array from csv file
"sectionCount" : TabSectionData.length
for (sCounter = 0; sCounter<tabs[tCounter].sectionCount; sCounter++){
"tabChildURL" : "Contents/Product Groups/"+this.tabData[tCounter]+"/"+tabs[tCounter].TabSectionData[sCounter]+"/order.csv",
"TabChildData" : $.getCsvArray(tabChildURL) //gets array from csv file
sections[sCounter] ={
"title" = tabs[tCounter].TabSectionData.[sCounter];
cCounter = 0;
for (cCounter = 0; cCounter<TabChildData.length; cCounter++){
children[cCounter]={
"title": tabs[tCounter].TabSectionData[sCounter].TabChildData.[cCounter]
}
}
}
}
}
}
您可以在函數內部運行循環並立即執行該函數。 我創建了一個片段作為示例。
var obj = { name: 'My Object', sections: (function () { var result = []; for (var i = 0; i < 10; i++) { var it = {}; result[i] = it; it.title = 'Hello'; it.children = []; for (var j = 0; j < i; j++) { it.children[j] = 'children' + j; } } return result; })() }; var json = JSON.stringify(obj, null, 4); jQuery('pre').append(json);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <pre></pre>
關於您的問題,“您是否可以在對象[literal]中使用for循環”,也許要創建屬性列表,您可以執行以下操作:
將for
循環包含在立即調用的函數內。 從該函數return
循環結果。
例如:
我想使用for循環動態添加屬性數組。
var items = {
list : (function(){ // immediately invoked function
var arr = []; // array
for (var i = 0; i < 4; i++)
{
arr.push('item no. '+i); // add each item to array
}
return arr; // return the array as value of the list property
})()
}
結果:
items = {列表:[“ 0號商品”,“ 1號商品”,“ 2號商品”,“ 3號商品”]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.