R4E Group
R4E Group

Reputation: 37

convert Json array key value to js array

$AllSorts = array();
$AllSorts[] = array('type'=>'العدد الكلي','num'=>$allSize);

$AllSorts[] = array('type'=>'عدد الطلاب','num'=>$studentSize);

$AllSorts[] = array('type'=>'عدد الأساتذة','num'=>$tchSize);

$AllSorts[] = array('type'=>'عدد المدراء','num'=>$managerSize);

$AllSorts[] = array('type'=>'عدد مراقبي الدوام','num'=>$atsSize);

$AllSorts[] = array('type'=>'عدد مراقبي الحافلات','num'=>$bgrSize);

$AllSorts[] = array('type'=>'عدد مراقبي الرسوم','num'=>$fgrSize);


$JsonData = json_encode($AllSorts);
echo $JsonData;

this is the php code to get thw json date

var jsonData = '';
    
$.get('../Functions/Ajax/GetSortingData.php?id='+schoolId, function(data){
            jsonData = JSON.parse(data);
    console.log(jsonData);
    
       });
var labels = [];
var datas = [];
for(const obj of jsonData){
   labels.push(obj.type);
   datas.push(obj.num);
}
console.log(datas);

and this is the javascript

Upvotes: 1

Views: 65

Answers (2)

Unmitigated
Unmitigated

Reputation: 89294

Just loop over the array of objects.

var arr = [
  {type: "العدد الكلي", num: 14},
  {type: "عدد الطلاب", num: 8},
  {type: "عدد الأساتذة", num: 2},
  {type: "عدد المدراء", num: 1},
  {type: "عدد مراقبي الدوام", num: 1},
  {type: "عدد مراقبي الحافلات", num: 1},
  {type: "عدد مراقبي الرسوم", num: 1}
];
var labels = [];
var datas = [];
for(const obj of arr){
  labels.push(obj.type);
  datas.push(obj.num);
}
console.log("Labels", labels);
console.log("Datas", datas);

For your particular case, you need to be looping over the array in the callback for the AJAX call, as AJAX is asynchronous.

$.get('../Functions/Ajax/GetSortingData.php?id='+schoolId, function(data){
            jsonData = JSON.parse(data);
            console.log(jsonData);
            var labels = [];
            var datas = [];
            for(const obj of jsonData){
               labels.push(obj.type);
               datas.push(obj.num);
            }
            console.log(datas);
       });

Upvotes: 0

Lawrence Cherone
Lawrence Cherone

Reputation: 46610

Use map:

const array = [{
    type: "العدد الكلي",
    num: 14
  },
  //.snip
]

const type = array.map(i => i['type'])
console.log(type)

const num = array.map(i => i['num'])
console.log(num)

Upvotes: 1

Related Questions