Object.keys(data).forEach不循环

时间:2017-11-27 10:16:08

标签: javascript arrays json

我试图获取一个值形式的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)
    }  
});

这里的输出是:仅第一个结果,并且throws 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的新手,所以我无法解决。我尝试了很多参考来解决这个问题,但我做不到。请尝试解决这个问题。提前谢谢。

2 个答案:

答案 0 :(得分:3)

  

他只是第一个结果并且抛出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"

答案 1 :(得分:2)

您的密钥和索引混合了一些东西。 您可以使用Object.values (ES8 only)来获取精确值并保留键部分。然后迭代它们并制作你的字符串。

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


Object.values(data).forEach(function(values) {    
   
   values.forEach(value => {
      console.log(`branchId: ${value.branchId} BranchName: ${value.branchName} Department Name: ${value.departmentName}`);
   });
    
});