将json的一部分提取到另一个对象中并保持两者之间的链接

时间:2013-03-06 11:01:12

标签: javascript json

{
   "data": [
      {
         "date": "2013-03-07",
         "id": "2",
         "vt_color": "#548dd4",
         "vt_name": "follow up",
         "duration": "20",
         "time_booked": "12:00:00",
         "stats": "booked",
         "doctor_id": "00002",
         "patient_id": "00003"
      },
      {
         "date": "2013-03-08",
         "id": "3",
         "vt_color": "#76923c",
         "vt_name": "ultrasound",
         "duration": "30",
         "time_booked": "08:00:00",
         "stats": "booked",
         "pt_name": "demo patien",
         "dr_name": "Momen Alzalabany",
         "doctor_id": "00002",
         "patient_id": "00009"
      }
   ] 
}

我想要的是创建另一个数组,包括vt_name,vt_color和数据索引 所以我使用jquery

var words = [];

$.each(arr['data'],function(ref){
    words[this.doctor_id].push({name: this.vt_color,color: this.vt_name,index:ref});
});
console.log(koko);

失败:单词[this.do_id]未定义....

我该怎么做?我希望结果是

抱歉,我是json / js的新手

我想在php中获得结果

['00002'=>[
            ['name'=>'follow up','color'=>'#548dd4',index=>[0,3,4]],
            ['name'=>'ultrasound','color'=>'#769dd4',index=>[1,5,8]]
          ]
 ]

1 个答案:

答案 0 :(得分:0)

  1. 将单词类型更改为object(而非数组),因为您需要一个带字符串的地图(例如'00002')作为键:

    var words = {};
    
  2. 您想要添加到不存在的数组。您需要先创建它:

    words[this.doctor_id] = words[this.doctor_id] || []; // creates an array if not already existing
    words[this.doctor_id].push({name: this.vt_color,color: this.vt_name,index:ref});