0

I am getting keys and values from php associative array to jquery object:

$names = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
$js = json_encode($names);
echo 'var names= ' . $js . ";";

Now I know how to iterate through all of the names and get their key and value:

$.each(names, function(key, value){
   alert(key + value);
});

But I need only specific value. For example how can I get only "Ben" and "37" without iterating through all the names?

7
  • 1
    console.log(names.Ben); ? Commented Jan 15, 2016 at 16:18
  • But I don't know the key. I don't know that the name is Ben. I would like to get the key as well as the value Commented Jan 15, 2016 at 16:19
  • Try to add new Array() like: echo 'var names= new Array( ' . $js . ");"; Commented Jan 15, 2016 at 16:21
  • 2
    @matip if you don't know the key then how do you know what you're trying to retrieve? do you know the value? Commented Jan 15, 2016 at 16:23
  • I would like to get second key and value. Is that possible? Commented Jan 15, 2016 at 16:23

1 Answer 1

4

You can do this using Object.keys

var index = 1; // the nth key you want to fetch, 1 will be second
key = Object.keys(names)[index];
value = names[key];

console.log(key + ' -> ' + value);

Will output

Ben -> 37
Sign up to request clarification or add additional context in comments.

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.