如何使用 ES5 使用多个值查找数组中对象的索引?

How to find index of object in array using multiple values with 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;

ES6+

您可以使用 .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:

使用.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];
}

获取索引--您可以将索引值作为过滤方法的一部分返回。查看文档以获取更多示例。

听起来你可以直接使用 filter 如果我没看错你的问题。例如:

 var theItem = 'however your item numbers look'
 var matches = posArr.filter(function(x) { return x.item === theItem })

这将 return posArr 中所有事物的数组,这些事物具有 theItem

中指定的特定项目编号