2

I transferred a multidimensional array into JavaScript via <?php echo json_encode($my_array); ?> And I would like to compare entries of that JSON with other variables. So how could I get an object as string without the sub-entries?

Let's say my object is [Object { 1429={Object { 8766={...}, 8483={...}, 7345={...}}}}, Object { 9041={...}}]

So how could I get 1429 or 8766 as String? I know how to do that with a multidimensional array in PHP (there it is key()) - but what would it be in JavaScript?

3
  • In PHP the key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. There is no internal pointer in the js object. What do you expect the key function to do? Commented Nov 26, 2013 at 16:13
  • JavaScript does not have the concept of "array pointer" (and I seldom use it in PHP). But I can't figure out what your object/array looks like (posting fake JSON doesn't help) and what rules make you choose between 1429 and 8766. Can you please post some real code? Commented Nov 26, 2013 at 16:15
  • 3
    If you want to get at the key while iterating through an object then yes that can be done with JS/jQuery. Post your loop and we can assist. Commented Nov 26, 2013 at 16:20

2 Answers 2

1

In PHP the key() function simply returns the key of the array element that's currently being pointed to by the internal pointer.

for example (from manual):

<?php
 $array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');

// this cycle echoes all associative array
 // key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
    echo key($array).'<br />';
}
next($array);
}
?>

There is no such thing in the js like internal pointer in object, so there is no similar function.

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

1 Comment

Ah ok! Thank you! Then I'll have to find another solution.
1

Just an example of what I think you want. You can extend on this more.

var obj = {
    "5": "some",
    "8": "thing"
};
var keys = $.map(obj, function (value, key) {
    return key;
});
//result keys: ["5", "8"]

JSFIDDLE DEMO - open the console to see the result.

1 Comment

Thank you! My json is not well formatted - so in my case it returns just [0, 1] because i need it for the highest level in my array, not the lowest.

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.