Siva
Siva

Reputation: 1859

How to get numeric index of the equivalent key in associative array in javascript

var assoArray={
    "Test": 0,
    "Test 2": 2
}

In the above associative array, i could get value of Test2 by

var valofTest2 = assoArray["Test 2"]

how do i get the equivalent numeric index of "Test 2" ? would expect 1 as an output

PS: am new to JS

Upvotes: 0

Views: 516

Answers (2)

ssube
ssube

Reputation: 48267

There isn't one.

Before the latest specification updates (ES6), the order of keys in an object was entirely undefined and could return in a different order every time.

With ES6, the order is defined as the order they were added in, so you can get close with something like Object.keys(foo).indexOf('Test 2'). It will give you the index in the array of keys, which should be stable for the life of the object and property.

Upvotes: 3

Elheni Mokhles
Elheni Mokhles

Reputation: 4001

function indexOfAtrr(obj,attr) {
    i = 0;
    $.each(obj, function(key, value) {
        if (key == attr) return i;
        i++;
    });
    return -1;
}

Upvotes: 0

Related Questions