如何循环JSON数据对象数组

时间:2018-07-18 09:23:05

标签: json ajax laravel

我有一个Ajax请求,该请求运行以下代码:

$all_jobs = JobPost::select('id','job_title','job_category','application_deadline')
    ->where('application_deadline','>=',$today)
    ->where('job_published_status',0)
    ->where('job_posts.status','Active')
    ->orderBy('id','DESC')
    ->where('user_id',$request->id)
    ->paginate(20);
    return response()->json($all_jobs);

记录返回的数据时,我得到以下结构:

console.log(data)

enter image description here

现在,当我使用以下方法遍历数据时:

$.each(data, function(index,company){ console.log(company); });

console.log(company);返回以下结构:

0:{id: 12, job_title: "Job Title for 12", job_category: "engineer-architects", application_deadline: "2018-07-27 00:00:00"} 1:{id: 11, job_title: "Job Title for 11", job_category: "garments-textile", application_deadline: "2018-07-19 00:00:00"} 2:{id: 10, job_title: "Job Title for 10", job_category: "accounting-finance", application_deadline: "2018-07-19 00:00:00"} 3:{id: 2, job_title: "Game Developer", job_category: "bank-non-bank-fin-institution", application_deadline: "2018-07-19 00:00:00"} 4:{id: 1, job_title: "Game Developer", job_category: "accounting-finance", application_deadline: "2018-07-26 00:00:00"} length:5

但是如果我尝试在循环中使用console.log(company[0])访问

我得到这样的数据:

{id: 12, job_title: "Job Title for 12", job_category: "engineer-architects", application_deadline: "2018-07-27 00:00:00"}

但我也收到一条错误消息:

Uncaught TypeError: Cannot read property '0' of null

此外,当我尝试像这样在循环中访问属性时:

console.log(company[0].id)

我收到以下错误:

Uncaught TypeError: Cannot read property 'id' of undefined

现在我的问题是如何遍历data并获取所有值。

2 个答案:

答案 0 :(得分:0)

您将必须像这样使用每个函数中提供的索引:

$.each(data, function(index,company){
     console.log(data[index]); // here is the company object
     // or access the company directly
     console.log(company); // same here = company object
});

答案 1 :(得分:0)

进入company对象,您将获得当前数组的索引,即您必须在没有索引的情况下访问所需的属性,即console.log(company.id)循环内的each。如果要使用索引进行访问,则应在循环内使用data对象,即console.log(data[0])console.log(data[0].id)console.log(data[index])