获取数组内对象的索引,匹配条件

我有这样一个数组:


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

如何在不迭代整个数组的情况下获取与条件匹配的对象的索引?


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


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


繁星coding
浏览 1034回答 3
3回答

哆啦的时光机

截至2016年,您应该使用Array.findIndex(ES2015 / ES6标准):a = [&nbsp; {prop1:"abc",prop2:"qwe"},&nbsp; {prop1:"bnmb",prop2:"yutu"},&nbsp; {prop1:"zxvz",prop2:"qwrq"}];&nbsp; &nbsp;&nbsp;index = a.findIndex(x => x.prop2 ==="yutu");console.log(index);谷歌Chrome,Firefox和Edge支持它。对于Internet Explorer,链接页面上有一个polyfill。表现说明函数调用很昂贵,因此对于非常大的数组,简单的循环将比以下方式执行得更好findIndex:let test = [];for (let i = 0; i < 1e6; i++)&nbsp; &nbsp; test.push({prop: i});let search = test.length - 1;let count = 100;console.time('findIndex/predefined function');&nbsp; &nbsp; let fn = obj => obj.prop === search;&nbsp; &nbsp; for (let i = 0; i < count; i++)&nbsp; &nbsp; &nbsp; &nbsp; test.findIndex(fn);console.timeEnd('findIndex/predefined function');console.time('findIndex/dynamic function');&nbsp; &nbsp; for (let i = 0; i < count; i++)&nbsp; &nbsp; &nbsp; &nbsp; test.findIndex(obj => obj.prop === search);console.timeEnd('findIndex/dynamic function');console.time('loop');&nbsp; &nbsp; for (let i = 0; i < count; i++) {&nbsp; &nbsp; &nbsp; &nbsp; for (let index = 0; index < test.length; index++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (test[index].prop === search) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }console.timeEnd('loop');与大多数优化一样,只有在实际需要时才应谨慎应用。

跃然一笑

如何获得与条件匹配的对象索引(不沿数组迭代)?你不能,什么都有通过数组(至少一次)进行迭代。如果条件变化很大,那么你将不得不循环并查看其中的对象以查看它们是否与条件匹配。但是,在具有ES5功能的系统上(或者如果安装了垫片),可以相当简洁地完成该迭代:var index;yourArray.some(function(entry, i) {&nbsp; &nbsp; if (entry.prop2 == "yutu") {&nbsp; &nbsp; &nbsp; &nbsp; index = i;&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }});它使用new(ish)Array#some函数,它循环遍历数组中的条目,直到你给它的函数返回true。我给它的函数保存了匹配条目的索引,然后返回true以停止迭代。或者当然,只需使用for循环。您可以在其他答案中介绍各种迭代选项。但是如果你总是要为这个查找使用相同的属性,并且如果属性值是唯一的,你可以只循环一次并创建一个对象来映射它们:var prop2map = {};yourArray.forEach(function(entry) {&nbsp; &nbsp; prop2map[entry.prop2] = entry;});(或者,您可以再次使用for循环或任何其他选项。)然后,如果您需要找到条目prop2 = "yutu",您可以这样做:var entry = prop2map["yutu"];我把这称为“交叉索引”数组。当然,如果删除或添加条目(或更改其prop2值),则还需要更新映射对象。

慕慕森

var CarId = 23;//x.VehicleId property to match in the object arrayvar carIndex = CarsList.map(function (x) { return x.VehicleId; }).indexOf(CarId);对于基本数组编号,您也可以这样做:var numberList = [100,200,300,400,500];var index = numberList.indexOf(200); // 1如果在数组中找不到值,则会得到-1。
打开App,查看更多内容
随时随地看视频慕课网APP