简体   繁体   English

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

[英]How to find index of object in array using multiple values with ES5?

I am currently looking up objects in an array using one value, item number. 我目前正在使用一个值(项目编号)在数组中查找对象。 However, if there happened to be multiple orders that both had the same item number on them, how could the particular object index be looked up using both values? 但是,如果碰巧有多个订单都具有相同的项目编号,那么如何使用两个值来查找特定的对象索引?

Object is structured in such a manner: 对象的构造方式如下:

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

Here is how I am looking the objects up now: 这是我现在查找对象的方式:

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

Sounds like you could just use filter if I am reading your question correctly. 听起来如果我正确阅读您的问题,您可以只使用filter For example: 例如:

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

This will return an array of all things in posArr that have a particular item number specified in theItem 这将返回所有的东西在一个数组posArr那些在指定的特定项目编号theItem

ES6+ ES6 +

You can use .findIndex() 您可以使用.findIndex()

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

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

ES5: ES5:

Using .filter(): 使用.filter():

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter https://developer.mozilla.org/zh-CN/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. 查看文档以获取更多示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM