我有一个这样的数组:

[{prop1:"abc",prop2:"qwe"},{prop1:"bnmb",prop2:"yutu"},{prop1:"zxvz",prop2:"qwrq"},...]

我怎么能得到对象的索引,匹配的条件,而不是在整个数组上迭代?

例如,给定prop2=="yutu",我想获得索引1。

我看到过. indexof(),但认为它用于简单的数组,如["a1","a2",…]。我还检查了$.grep(),但这返回对象,而不是索引。


当前回答

var CarId = 23;

//x.VehicleId property to match in the object array
var carIndex = CarsList.map(function (x) { return x.VehicleId; }).indexOf(CarId);

对于基本数组号,你也可以这样做:

var numberList = [100,200,300,400,500];
var index = numberList.indexOf(200); // 1

如果它在数组中找不到值,就会得到-1。

其他回答

var index;
yourArray.some(function (elem, i) {
    return elem.prop2 === 'yutu' ? (index = i, true) : false;
});

遍历数组的所有元素。 它返回索引,如果条件不匹配则返回true或false。

重要的是显式返回值为true(或布尔结果为true的值)。单个赋值是不够的,因为索引可能为0 (Boolean(0) === false),这不会导致错误,但会禁用中断迭代。

Edit

上面的一个更简短的版本:

yourArray.some(function (elem, i) {
    return elem.prop2 === 'yutu' && ~(index = i);
});

使用Array.reduce()的一个步骤-没有jQuery

var items = [{id: 331}, {id: 220}, {id: 872}];

var searchIndexForId = 220;
var index = items.reduce(function(searchIndex, item, index){
  if(item.id === searchIndexForId) { 
    console.log('found!');
    searchIndex = index;
  }
  return searchIndex;
}, null);

如果没有找到索引,将返回null。

我怎么能得到对象的索引匹配的条件(没有迭代沿数组)?

你不能,某些东西必须遍历数组(至少一次)。

如果条件变化很大,则必须遍历并查看其中的对象,以确定它们是否与条件匹配。然而,在一个带有ES5特性的系统上(或者如果你安装了一个shim),这个迭代可以相当简单地完成:

var index;
yourArray.some(function(entry, i) {
    if (entry.prop2 == "yutu") {
        index = i;
        return true;
    }
});

它使用了新的(ish) array# some函数,该函数循环遍历数组中的条目,直到您赋予它的函数返回true。我给它的函数保存匹配条目的索引,然后返回true以停止迭代。

当然,也可以使用for循环。您的各种迭代选项都包含在另一个答案中。

但如果你总是要使用相同的属性进行查找,如果属性值是唯一的,你可以只循环一次,并创建一个对象来映射它们:

var prop2map = {};
yourArray.forEach(function(entry) {
    prop2map[entry.prop2] = entry;
});

(或者,同样,您可以使用for循环或任何其他选项。)

然后如果你需要找到prop2 = "yutu"的条目,你可以这样做:

var entry = prop2map["yutu"];

我称之为“交叉索引”数组。当然,如果您删除或添加条目(或更改它们的prop2值),您也需要更新映射对象。

你可以以以下方式使用Array.prototype.some()(正如在其他答案中提到的):

https://jsfiddle.net/h1d69exj/2/

function findIndexInData(data, property, value) {
    var result = -1;
    data.some(function (item, i) {
        if (item[property] === value) {
            result = i;
            return true;
        }
    });
    return result;
}
var data = [{prop1:"abc",prop2:"qwe"},{prop1:"bnmb",prop2:"yutu"},{prop1:"zxvz",prop2:"qwrq"}]



alert(findIndexInData(data, 'prop2', "yutu")); // shows index of 1

使用Array.map()和Array.indexOf(string)

const arr = [{ 提案 1: “ABC”, 提案2:“QWE” }, { 提案 1: “bnmb”, 提案2:“玉兔” }, { 提案1:“ZXVZ”, 提案2:“QWRQ” }] const index = arr.map(i => i.prop2).indexOf(“yutu”); 控制台.log(索引);