使用json响应的jquery中的对象

时间:2018-08-16 07:13:07

标签: php jquery json javascript-objects

我想使用从控制器返回的json响应在jQuery中创建对象

var cellContents = {'29-08-2018': '20','18-08-2018': '60'};

这是我想要的期望格式,下面是我的json响应

{"status":1,"result":[{"followup_datee":"17-08-2018","date":[{"fcount":"1"}]},{"followup_datee":"18-08-2018","date":[{"fcount":"1"}]}]}

我尝试了一些代码来制作所需的格式,但失败了,这是我尝试过的代码

var arr2 = [];
      //var cellContents = JSON.parse(data.result);

      for(var i=0; i<data.result.length; i++){
        var arr = [];
        for(var j=0; j<data.result[i].date.length; j++)
        { 
        arr.push(parseInt(data.result[i].date[j].fcount));
        } 
        var test = [data.result[i].followup_datee];
        arr2.push(test.concat(arr));
        } 
        var jsonString = JSON.stringify(arr2);
      console.log(jsonString);

尝试此代码后,我在控制台中得到了这样的响应

[["17-08-2018",1],["18-08-2018",1]]

这是我在php中使用的控制器

 public function getLeadcount()
{
    $status = 1;
    $arr = [];
    $sess = $this->session->userdata('user_id');
    $result = $this->mdl_lead_registration->getLeaddate($sess);
    if(!empty($result))
    {
        $status = 1;
        foreach($result as $res)
        {
            $res->{'date'} = '';
            $res->date = $this->mdl_lead_registration->getLeadcount($sess,$res->followup_datee);
        }

    }

   echo json_encode(array("status" => $status,"result" => $result));
}

我想你们都明白我的问题。任何形式的帮助都是有意义的。

1 个答案:

答案 0 :(得分:0)

使用以下代码:

var data = {"status":1,"result":[{"followup_datee":"17-08-2018","date":[{"fcount":"1"}]},{"followup_datee":"18-08-2018","date":[{"fcount":"1"}]}]};

var obj = {};

for (var i = 0; i < data.result.length; i++){
  obj[data.result[i].followup_datee] = parseInt(data.result[i].date[0].fcount);
  // Here you change the property.
  // In js you can access to an object's property like an array,
  // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors.

  // If you want to use the count as a string, use instead:
  // obj[data.result[i].followup_datee] = data.result[i].date[0].fcount;
}

console.log(obj);