Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

indexOf( object) in javascript [duplicate]

Tags:

javascript

Error in following code:-

var x = [{id: 'abc'}, {id: 'xyz'}];

var index = x.indexOf({id: 'abc'});

What's the syntax for above?

like image 803
Sangram Singh Avatar asked Mar 19 '26 02:03

Sangram Singh


2 Answers

You should pass reference to exactly the same object you have defined in the array:

var a = {id: 'abc'},
    b = {id: 'xyz'};

var index = [a, b].indexOf(a);  // 0
like image 92
VisioN Avatar answered Mar 21 '26 16:03

VisioN


Objects are only equal to each other if they refer to the exact same instance of the object.

You would need to implement your own search feature. For example:

Array.prototype.indexOfObject = function(obj) {
    var l = this.length, i, k, ok;
    for( i=0; i<l; i++) {
        ok = true;
        for( k in obj) if( obj.hasOwnProperty(k)) {
            if( this[i][k] !== obj[k]) {
                ok = false;
                break;
            }
        }
        if( ok) return i;
    }
    return -1; // no match
};

var x = [{id: 'abc'}, {id: 'xyz'}];
var index = x.indexOfObject({id: 'abc'}); // 0
like image 35
Niet the Dark Absol Avatar answered Mar 21 '26 14:03

Niet the Dark Absol