【问题标题】:Object in jquery using json responsejquery中的对象使用json响应
【发布时间】:2018-08-16 07:13:07
【问题描述】:

我想使用从我的控制器返回的 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));
}

我想你们都理解我的问题。任何形式的帮助都是可观的。

【问题讨论】:

  • 请举个例子——你从服务器得到什么,js结果是什么,你想要什么结果。
  • 我想要这样的结果 {'17-08-2018': '1','18-08-2018': '1'} 但我得到了这样的结果 [["17-08 -2018",1],["18-08-2018",1]]
  • 为什么你的date 属性是一个数组?你想要{'17-08-2018': [1],'18-08-2018': [1]}这样的结果吗?
  • 我不想在我的结果中使用任何数组格式我想要日期作为我的键并算作我的值
  • 但是你有dates 的数组! Dio 你想得到它们的总和吗?

标签: php jquery json javascript-objects


【解决方案1】:

使用以下代码:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多