d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Json Encode
Add Reply New Topic New Poll
Member
Posts: 8,635
Joined: Dec 28 2007
Gold: 87.00
Aug 8 2012 06:10am
So I have a javascript function call in php onChange and it uses json_encode to convert array so I can send it as javascript function parameter.

json_encode:
Code
[{"Id":8,"Mp":1301},{"Id":9,"Mp":1301},{"Id":3,"Mp":1301},{"Id":2,"Mp":1301},{"Id":4,"Mp":0},{"Id":10,"Mp":1315},{"Id":7,"Mp":0},{"Id":6,"Mp":0},{"Id":1,"Mp":0},{"Id":5,"Mp":0}]


javascript:
Code
function function_to_call(array){
//action I need to do
}


In javascript I need to be able to handle the array so I can pick up Mp value for specific Id. Example for Id 10 I want to alert the 1315. But so far when I try to alert the array alone it only gives output:
Code
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

I also tried using
Code
for(key in array){alert(array[key])}

Which alerts [object Object] for each {Id,Mp} set, how I can get out the Id value and Mp value?

Not really familiart with JS so pretty clueless how to do this, any suggestions how could I get this to work?
Member
Posts: 2,579
Joined: Jun 1 2012
Gold: 1,524.00
Aug 8 2012 06:43am
It is basically a 2-dimensional array of objects;

This code will work to iterate over each value:

Code

var a = [{
   "Id": 8,
   "Mp": 1301},
{
   "Id": 9,
   "Mp": 1301},
{
   "Id": 3,
   "Mp": 1301},
{
   "Id": 2,
   "Mp": 1301},
{
   "Id": 4,
   "Mp": 0},
{
   "Id": 10,
   "Mp": 1315},
{
   "Id": 7,
   "Mp": 0},
{
   "Id": 6,
   "Mp": 0},
{
   "Id": 1,
   "Mp": 0},
{
   "Id": 5,
   "Mp": 0}]

for (var key in a) {
   if (a.hasOwnProperty(key)) {
       var obj = a[key];
       for (var val in obj) {
           var id = val;
           alert(id + ":" + obj[val]);
       }
   }
}​


And here's a jsfiddle link:
http://jsfiddle.net/GytT5/
Member
Posts: 8,635
Joined: Dec 28 2007
Gold: 87.00
Aug 8 2012 06:59am
Quote (Schwag @ 8 Aug 2012 14:43)
It is basically a 2-dimensional array of objects;

This code will work to iterate over each value:

And here's a jsfiddle link:
http://jsfiddle.net/GytT5/


Thanks.

Is this good way to do what I need, or is there better way of doing this?
Code
function function_to_call(array){
var taulu=new Array();
var tempId,tempMp,i=0;
for(var key in array){
 if(array.hasOwnProperty(key)){
  var obj = array[key];
  i=0;
  for (var val in obj){
   var id = val;
   if(i==0){
    tempId=obj[val];
    i++;
   }else
    tempMp=obj[val];
  }
  taulu[tempId]=tempMp;
 }
}
alert(taulu[10]);
}
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll