2

Hello i have returned array in json from jquery ajax call of php file. This array looks like this :

array(
'LANG_PORTFOLIO'=>'Portfolio',
'LANG_ABOUT'=>'Company',
);

is it possible somehow to get also first key dynamically?

In my jquery success code i have this :

 success: function (data) {
        alert(data[0][0]);
        alert(data.[1]);
        alert(data.LANG_PORTFOLIO);
 }

Only last mentioned works. But i cant use it dynamically.

I want to achieve something like this :

 for(var i in data){
     var key=data[0] //first key
     $("element[lang='"+key+"']").text(data.key); //add text with active language
 }

// i set lang parameter of elements equal to array 'leftside' keys.

Any help? Thanks

2
  • For what purpose you need first key? var key=data[0] Commented Feb 10, 2014 at 8:44
  • because this key equals to my elements attributes and thos i can change their content dynamically. Commented Feb 10, 2014 at 8:46

3 Answers 3

1

Well, there's no special thing for that, but you can use:

for (key in data) break;
//now key will be first key of your object

Thus, your loop will be like:

for(var i in data)
{
    for (key in data[i]) break; //first key of data[i]
    //here is why I doubt: data[i], but data.key ??
    $("element[lang='"+key+"']").text(data.key); 
}

(I'm not sure about logic, that's what I see from question's post. Especially I'm doubt because your JSON in PHP is 1D-array while in JSON you're operating on 2D)

Sign up to request clarification or add additional context in comments.

4 Comments

and this should be inner loop? substition for var key=data[0]?
I've updated, yep. The idea is to use for..in and break after first iteration
oh i'll try it :) will get back soon
Both of replies works. But u know 'key' is just pseudo. I dont have to do it in 2 steps but i wanted u to understand my purpose :)
1
for(var i in data){     
     $("element[lang='"+i+"']").text(data.[i]); //add text with active language
}

Comments

1

try this way to split your JSON array

success:function(data){
    $.each(data,function(key,value){
      $("element[lang='"+key+"']").text(value.LANG_PORTFOLIO);
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.