0

I have an array with objects. The objects have a property name. I want the index of the object where the property is equal to bart. How can i find the index of that object?

jonas vermeulen
  • 1,235
  • 5
  • 23
  • 40

5 Answers5

1
var data = [{ name: 'bart' }, { name: 'baz' }];

function getPropIndexByName(data, prop, str){

    var ret = []; //updated to handle multiple indexes

    $.each(data, function(k, v){
        if(v[prop] === str)
            ret.push(k);
    });

    return ret.length ? ret : null;
}

var result = getPropIndexByName(data,   //data source
                               'name',  //property name
                               'bart'); //property value

console.log(result);

http://jsfiddle.net/Le72k/1/

Johan
  • 35,120
  • 54
  • 178
  • 293
0

Something like this:

for (var key in myobject)
{
  console.log(key);
}
Paul Rad
  • 4,820
  • 1
  • 22
  • 23
0
var matches = jQuery.grep(array, function() {
    // this is a reference to the element in the array
    // you can do any test on it you want
    // return true if you want it to be in the resulting matches array
    // return false if you don't want it to be in the resulting matches array

    // for example: to find objects with the Amount property set to a certain value
    return(this.Amount === 100);
});
Neel
  • 11,625
  • 3
  • 43
  • 61
0

If you had:

var myArray = [{x: 1}, {x: 2}, {x: 3}];

To get the index of the first object where x === 2 I would do:

function indexOfFirstMatch (arr, condition) {
    var i = 0;

    for(;i < arr.length; i++) {
        if(condition(arr[i])) {
            return i;
        }
    }
    return undefined;
}

var index = indexOfFirstMatch(myArray, function (item) { return item.x === 2; });
// => 1

If you wanted to be a real maverick, you could extend Array:

Array.prototype.indexOfFirstMatch = function indexOfFirstMatch (condition) {
    var i = 0;

    for(;i < this.length; i++) {
        if(condition(this[i])) {
            return i;
        }
    }
    return undefined;
}

var index = myArray.indexOfFirstMatch(function (item) { return item.x === 2; });
// => 1
RichardTowers
  • 4,682
  • 1
  • 26
  • 43
0

If they were actually HTML elements under a single element you could do

index = $('#parentobject').index('[property="bart"]')
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202