用于动态创建对象的嵌套循环
Nested loop to dynamically create objects
我正在尝试创建一个循环或嵌套循环,它将创建一(1)个包含许多对象的数组:
// example of the object structure
obj0.country = distAttr[0];
obj0[municipo[0]] = econ[0];
obj0[municipo[1]] = edu[0];
obj0[municipo[2]] = gov[0];
obj0[municipo[3]] = health[0];
obj0[municipo[4]] = infra[0];
obj0[municipo[5]] = social[0];
obj1.country = distAttr[1];
obj1[municipo[0]] = econ[1];
obj1[municipo[1]] = edu[1];
obj1[municipo[2]] = gov[1];
obj1[municipo[3]] = health[1];
obj1[municipo[4]] = infra[1];
obj1[municipo[5]] = social[1];
// ... obj18
这就是我目前所拥有的:
// create all the objects, distAttr length is 19
for (var i = 0; i < distAttr.length; i++) {
window['obj'+i ] = {};
};
// distName length is 6
var number = distName.length;
// this loop I can't figure out
for (var j = 0; i < distName.length; j++) {
window['obj'+i ][municipo[j]] = econ[i];
};
// bind the objects to the array
for (var i = 0; i < distAttr.length; i++) {
chartArray[i] = window['obj'+i];
};
您可以在单个循环中构建对象:
// Set up some variables and the field values you will use:
var j,
obj,
ec = municipo[0],
ed = municipo[1],
go = municipo[2],
he = municipo[3],
in = municipo[4],
so = municipo[5];
// Loop through the array.
for (i = 0; i < distAttr.length; i++) {
// Create an object with a country field.
obj = { country: distAttr[i] };
// Populate the other fields.
obj[ec] = econ[i];
obj[ed] = edu[i];
obj[go] = gov[i];
obj[he] = health[i];
obj[in] = infra[i];
obj[so] = social[i];
// Set the array index to contain the object
// (and if you need it then create a global object `objx`
// - not sure if you need it though.)
chartArray[i] = window['obj'+i] = obj;
};
相关文章:
- 动态创建嵌套的JSON对象父对象和子对象
- 用于动态创建对象的嵌套循环
- 如何在 Javascript 中创建一个模拟 100 行和 10 列网格的嵌套循环
- 在嵌套循环中创建事件处理程序的效率:我在这里创建了 1440 个函数
- 动态创建嵌套的 JSON 对象
- JavaScript-如何使用递归创建变量嵌套循环
- 循环遍历嵌套的json对象并显示kay/value对
- Javascript:嵌套循环以在VMware vCenter中创建目录树
- 使用不带嵌套循环的数组过滤对象数组js
- 嵌套循环未形成完整对象 - 问题
- 在使用jSON对象之前,是否需要创建嵌套的jSON对象?
- 优化嵌套循环,使用jQuery创建HTML元素
- 从嵌套的json对象中创建新的数组
- 循环遍历嵌套的json对象
- 如何动态创建复杂/嵌套的js对象
- 如何正确创建嵌套的JSON对象
- 正在创建嵌套的Javascript对象
- 为嵌套的 JSON 对象创建 GWT 叠加
- 创建嵌套循环以在javascript中构建菜单
- 从 SQL 结果创建嵌套的 JSON 对象