我创建了一个键值映射,如下所示,deMapping包含来自不同来源的数据,如RBSK等。 现在我想读取RBSK和其他源中的所有值,并希望在foreach循环中运行,如: deMapping.forEach(function(data)
var deMapping = {
RBSK: {'dsUID': 'tdTwLUxcQ8R', rootNodeName: 'RBSK_GIS_Indicator', orgUnitTagName: 'MCTSCode', des: [
{
xmlid: "Childhood_Diseases_0_6_Female",
dataElement: "oV163sbcJ0N",
categoryOptionCombo: "Cmzbo9LD8pJ"
},
{
xmlid: "Childhood_Diseases_0_6_Male",
dataElement: "oV163sbcJ0N",
categoryOptionCombo: "PnAVAPG4yvb"
},
{
xmlid: "Childhood_Diseases_7_18_Female",
dataElement: "cEPledgs7rd",
categoryOptionCombo: "Cmzbo9LD8pJ"
},
{
xmlid: "Childhood_Diseases_7_18_Male",
dataElement: "cEPledgs7rd",
categoryOptionCombo: "PnAVAPG4yvb"
},
{xmlid: "Deficiencies_0_6_Female", dataElement: "gKupqkIhW4n", categoryOptionCombo: "Cmzbo9LD8pJ"},
{xmlid: "Deficiencies_0_6_Male", dataElement: "gKupqkIhW4n", categoryOptionCombo: "PnAVAPG4yvb"},
{xmlid: "Deficiencies_7_18_Female", dataElement: "FuEnn0bLuoT", categoryOptionCombo: "Cmzbo9LD8pJ"},
{xmlid: "Deficiencies_7_18_Male", dataElement: "FuEnn0bLuoT", categoryOptionCombo: "PnAVAPG4yvb"},
{
xmlid: "Developmental_dealy_and_disability_0_6_Female",
dataElement: "v37HBq7C72j",
categoryOptionCombo: "Cmzbo9LD8pJ"
},
{
xmlid: "Developmental_dealy_and_disability_0_6_Male",
dataElement: "v37HBq7C72j",
categoryOptionCombo: "PnAVAPG4yvb"
},
{
xmlid: "Developmental_dealy_and_disability_7_18_Female",
dataElement: "S1WMlAKnF8Z",
categoryOptionCombo: "Cmzbo9LD8pJ"
},
{
xmlid: "Developmental_dealy_and_disability_7_18_Male",
dataElement: "S1WMlAKnF8Z",
categoryOptionCombo: "PnAVAPG4yvb"
},
{
xmlid: "defect_at_birth_0_6_Female",
dataElement: "JJO3utHjb3l",
categoryOptionCombo: "Cmzbo9LD8pJ"
},
{xmlid: "defect_at_birth_0_6_Male", dataElement: "JJO3utHjb3l", categoryOptionCombo: "PnAVAPG4yvb"},
{
xmlid: "defect_at_birth_7_18_Female",
dataElement: "qoVmtykHboz",
categoryOptionCombo: "Cmzbo9LD8pJ"
},
{xmlid: "defect_at_birth_7_18_Male", dataElement: "qoVmtykHboz", categoryOptionCombo: "PnAVAPG4yvb"}
]
}
}
答案 0 :(得分:0)
deMapping
是一个对象,因此您无法在其上运行forEach
。
相反,请选择for (var prop in deMapping)
for...in(并根据需要为每个包含的对象嵌套循环)。
for (var prop in deMapping) {
var subObj = deMapping[prop];
for (var subProp in subObj) { // subObj is what you call RBSK, we are looping on it now
console.debug(subProp, ":", subObj[subProp]); // will output 'dsUID': 'tdTwLUxcQ8R', rootNodeName: 'RBSK_GIS_Indicator', ... at each loop
}
}
使用ES6,您还可以使用for...of方法,该方法适用于对象,字符串......
编辑:
访问des
属性并迭代其对象,然后迭代对象属性本身。
for (var prop in deMapping) {
var subObj = deMapping[prop];
for (var subProp in subObj) { // subObj is what you call RBSK, we are looping on it now
if (subProp === "des") {
subObj[subProp].forEach(function(resObj) {
for (var prop in resObj) {
console.debug(prop, ":", resObj[prop]);
}
});
}
}
}