javascript - 如何使用 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+
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.
推荐阅读
- javascript - HTML5 必需标记不适用于我的 javascript 创建的函数
- docker - How does docker-compose create aliases for link ips
- machine-learning - 学习曲线:训练集大小应该递增还是随机选择?
- javascript - 仅当所有字段都有效时才反应最终形式我想处理提交
- mobile - 有什么好的手机框架吗?
- python - 如何将 np.matrix 的每一行保存到 9 对 touple 数组中?
- javascript - 包括用于加速移动页面的外部 CSS 和 JS?
- d3.js - 如何在 d3.scaleTime() 轴刻度中禁止年份?
- intellij-idea - 如何创建一个通过热键插入字符的动作?
- python - PySpark:使用 goup 索引添加列