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?

4

5 回答 5

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/

于 2013-09-24T08:56:28.430 回答
0

如果它们实际上是单个元素下的 HTML 元素,您可以这样做

index = $('#parentobject').index('[property="bart"]')
于 2013-09-24T11:06:03.837 回答
0

如果你有:

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

要获取x === 2我要做的第一个对象的索引:

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

如果你想成为一个真正的特立独行者,你可以扩展 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
于 2013-09-24T09:41:34.797 回答
0

像这样的东西:

for (var key in myobject)
{
  console.log(key);
}
于 2013-09-24T08:52:53.027 回答
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);
});
于 2013-09-24T08:55:52.223 回答