简体   繁体   中英

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM