Zee
Zee

Reputation: 79

Can't figure out how to get from a JSON data object a specific value with AJAX

I'm beginner with JSON and AJAX. I have this PHP file with JSON data objects that i want to parse to get a specific value from the array. For example i want to get the ID="almCrit" :

Here is my JSON Obj :

$currentArrayData['configAlm'] = array(
  array('blocName' => 'blockAlarmeContent',     'blocLVTwoName' => 'boxLV2Content', 'label' => 'Criticité',         'id' => 'almCrit'),
  array('blocName' => 'blockAlarmeContent', 'blocLVTwoName' => 'boxLV2Content', 'label' => 'Sans supervision',  'id' => 'almSansSup'),
  array('blocName' => 'blockAlarmeContent', 'blocLVTwoName' => 'boxLV2Content', 'label' => 'Non nominale',      'id' => 'almNonNom)
);

and here is what i tried to do :

$.ajax({
     url: 'Pages/index.php',
     type:  'get',
     dataType: 'json',
     data: 'action=loadBlocSite',
     success:function(data){                
        arrayOfData = data;         
        currentValue = arrayOfData;                        
        $.each(arrayOfData['configAlm'], function(currentIdx, currentValue){
            console.log('alarme : '+ arrayOfData['configAlm']);  
        });                 
    }
});

console.log('alarme : '+ arrayOfData['configAlm']); outputs:-

alarme : [object Object],[object Object],[object Object]

I want to get the ID of the first [object Object]

I tried this console.log('alarme : '+ arrayOfData['configAlm'].id); but it gives me

undefined

Can someone please help me figure out how it works ? Thank you

Upvotes: 0

Views: 86

Answers (2)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72289

This:-

$.each(arrayOfData['configAlm'], function(currentIdx, currentValue){
   console.log('alarme : '+ arrayOfData['configAlm']);  
});  

Need to be :-

$.each(arrayOfData['configAlm'], function(currentIdx, currentValue){
   console.log('Id : '+ currentValue.id);  
});  

You need to use currentValue there

If you want to apply some condition check then you can do something like below:-

$.each(arrayOfData['configAlm'], function(currentIdx, currentValue){
   if(currentValue.id =="almCrit"){
     return false; // Will stop iteration immediately when id==almCrit
   } 
});  

Upvotes: 0

cнŝdk
cнŝdk

Reputation: 32145

In fact what you are doing here is that you are printing the array in each iteration of the .each, and you were trying to access the id property of the array.

You need to log currentValue content instead of arrayOfData:

$.each(arrayOfData['configAlm'], function(currentIdx, currentValue){
   console.log('blocName Id: '+ currentValue['blocName'].id);  
});

And to better see what's happening here you can just print the whole iterated element of the array like this:

$.each(arrayOfData['configAlm'], function(currentIdx, currentValue){
   console.log(JSON.stringify(currentValue));  
});

Upvotes: 2

Related Questions