仅通过嵌套结构中定义的JSON对象循环 - JQUERY

时间:2017-12-14 14:02:44

标签: javascript jquery

我有以下json结构(我为了简化而缩短了时间):

{
 "employees":{"0":"Name1 Surname1", "1":"Name2 Surname2"},
 "managers":{"0":"Name3 Surname3", "1":"Name4 Surname4"},
 "teamleaders":{"0":"Name5 Surname5", "1":"Name6 Surname6"},
}

如何通过JQuery员工循环?下面的代码给了我整个3个对象,我似乎无法根据对象名称对它们进行排序:

 $.each(item, function (i, item) {
    $.each(item, function (key, value) {
       //gives me ALL names and surnames            
       console.log(value);
     })
 });

2 个答案:

答案 0 :(得分:1)

不是迭代外部对象item,而是这样做。

var item = {
  "employees":{"0":"Name1 Surname1", "1":"Name2 Surname2"},
  "managers":{"0":"Name3 Surname3", "1":"Name4 Surname4"},
  "teamleaders":{"0":"Name5 Surname5", "1":"Name6 Surname6"},
}

$.each(item.employees, function(key, value) { ... }); 

答案 1 :(得分:1)

你可以使用普通的JS。

for (var employee in json.employees) {
    if (json.employees.hasownProperty(employee)) 
       console.log(json.employees[employee])   
}