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?
Asked
Active
Viewed 1,261 times
0
-
http://stackoverflow.com/questions/8668174/indexof-method-in-an-object-array – mitchfuku Sep 24 '13 at 08:54
-
is there no other option than write a loop? – jonas vermeulen Sep 24 '13 at 08:56
-
2If they were actually HTML elements under a single element you could do `index = $('#parentobject').index('[property="bart"]')` – iCollect.it Ltd Sep 24 '13 at 08:57
-
@TrueBlueAusie this was actually the answer i was looking for , thanks, you may ad it as an answer to this post too – jonas vermeulen Sep 24 '13 at 10:25
-
Have added as answer... Thanks. – iCollect.it Ltd Sep 24 '13 at 11:06
5 Answers
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);

Johan
- 35,120
- 54
- 178
- 293
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