我尝试获取一个值形式的json对象。

var data={
"1":[{"departmentID":1,"departmentName":"Adminstration","branchId":1,"branchName":"ABC"}],
"2":[{"departmentID":2,"departmentName":"HR","branchId":2,"branchName":"DEF"}]
};


Object.keys(data).forEach(function(element, key, _array) {
    console.log("branchId: "+element+" "+"BranchName : "+data[element][key].branchName)

    for(dept of data[element]) {
            console.log("Department name : "+dept.departmentName)
    }
});


这里的输出是:仅第一个结果并抛出branchName是未定义的异常。

但是,如果json对象具有多个对象,则可以正常工作。

var data={
"1":[{"departmentID":1,"departmentName":"Adminstration","branchId":1,"branchName":"ABC"}],
"2":[{"departmentID":2,"departmentName":"HR","branchId":2,"branchName":"XYZ"},
     {"departmentID":3,"departmentName":"Food","branchId":2,"branchName":"XYZ"}]
}


我认为,由于我是JavaScript新手,所以无法解决。我尝试了很多参考资料来解决此问题,但我做不到。请尝试解决此问题。提前致谢。

最佳答案

他仅第一个结果并抛出branchName是未定义的异常。


您需要更换

data[element][key].branchName




data[element][0].branchName


因为


element是键"1"
所以data[element]变成[{"departmentID":1,"departmentName":"Adminstration","branchId":1,"branchName":"ABC"}]
data[element][0]变为{"departmentID":1,"departmentName":"Adminstration","branchId":1,"branchName":"ABC"}
最后data[element][0].branchName"ABC"

07-27 13:35