这是我的JSON数据:
"data": [
{
"id": 1,
"username": "admin",
"name": "admin",
"email": "admin@admin.com",
"job_title": "admin",
"created_at": null,
"updated_at": null,
"admin_role": {
"id": 1,
"user_id": 1,
"name": "Admin",
"created_at": "2018-10-23 11:00:55",
"updated_at": "2018-10-23 11:00:58",
}
},
...
Run Code Online (Sandbox Code Playgroud)
我正在尝试运行foreach循环,这是我的javascript代码:
$.each(data, function (key, value) {
rows = rows + '<tr>';
rows = rows + '<td>' + value.username + '</td>';
rows = rows + '<td>' + value.admin_role.name + '</td>';
rows = rows + '<td data-id="' + value.id + '">';
rows = rows + '<button data-toggle="modal" data-target="#edit-item" class="btn btn-primary edit-item">Edit</button> ';
rows = rows + '<button class="btn btn-danger remove-item">Delete</button>';
rows = rows + '</td>';
rows = rows + '</tr>';
});
Run Code Online (Sandbox Code Playgroud)
但该行value.admin_role.name抛出一个错误:
user.js:66未捕获的TypeError:无法读取null的属性"name"
这是我运行时得到的console.log(value):
在访问对象的任何属性之前,最好检查对象是否为null或未定义.在您的情况下,admin_role为null,因此您会看到该错误.
将您的方法更改为:
$.each(data, function (key, value) {
var role_name = value.admin_role ? value.admin_role.name : '';
rows = rows + '<tr>';
rows = rows + '<td>' + value.username + '</td>';
rows = rows + '<td>' + role_name + '</td>';
rows = rows + '<td data-id="' + value.id + '">';
rows = rows + '<button data-toggle="modal" data-target="#edit-item" class="btn btn-primary edit-item">Edit</button> ';
rows = rows + '<button class="btn btn-danger remove-item">Delete</button>';
rows = rows + '</td>';
rows = rows + '</tr>';
});
Run Code Online (Sandbox Code Playgroud)