首页 > 解决方案 > 如何使用 ES5 使用多个值在数组中查找对象的索引?

问题描述

我目前正在使用一个值(项目编号)在数组中查找对象。但是,如果碰巧有多个订单上都有相同的商品编号,那么如何使用这两个值查找特定的对象索引?

对象的结构如下:

var object = {
    line: line,
    poNumber: purchaseOrder,
    item: item
};

这是我现在查找对象的方式:

var posArrInd = posArr.map(function (x) { return x.item; }).indexOf(String(item));
var po = posArr[posArrInd];
var poLine = po.line;

标签: javascriptecmascript-5

解决方案


ES6+

You can use .findIndex()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

var found = items.findIndex(function(itm) {
   return itm.number1 === number1 && itm.number2 === number2;
});

ES5:

Using .filter():

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

var foundItems = items.filter(function(itm) {
   return itm.number1 === number1 && itm.number2 === number2;
});

if (foundItems && foundItems.length > 0) {
 var itemYouWant = foundItems[0];
}

Getting the index--you can have the index value returned as part of the filter method. Check out the docs for more examples.


推荐阅读