JQuery получить индекс объекта, где поле равно значению

0

У меня есть массив с объектами. Объекты имеют имя свойства. Я хочу индекс объекта, где свойство равно bart. Как я могу найти индекс этого объекта?

Теги:

5 ответов

0
Лучший ответ

Если бы они были элементами HTML под одним элементом, вы могли бы сделать

index = $('#parentobject').index('[property="bart"]')
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/

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

Если вы хотите быть настоящим maverick, вы можете расширить 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
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);
});
0

Что-то вроде этого:

for (var key in myobject)
{
  console.log(key);
}
  • 0
    для или foreach это?

Ещё вопросы

Сообщество Overcoder
Наверх
Меню