简体   繁体   English

在JavaScript中从数组中查找索引号

[英]Finding Index # from Array in JavaScript

I would like to loop through an array of elements and find the index # of the one that matches certain criteria. 我想遍历元素数组并找到与某些条件匹配的元素的索引号。 Take the following array: 采取以下数组:

services: [
  { _id: <ObjectId>,
    name: "initiating"
  },
  { _id: <ObjectId>,
    name: "evaluating"
  },
  { _id: <ObjectId>,
    name: "servicing"
  },
]

How would I loop through this array and pull out the array index # of the object where the property "name" is equal to "evaluating" (ie - array element #1)? 我将如何遍历此数组并在属性“名称”等于“求值”的情况下(即-数组元素#1)拉出对象的数组索引号?

Try Array.prototype.findIndex : 尝试Array.prototype.findIndex

 const services = [ { _id: 1, name: "initiating" }, { _id: 2, name: "evaluating" }, { _id: 3, name: "servicing" }, ]; console.log( services.findIndex(({ name }) => name === 'evaluating') ); 

 let services = [{ _id: 0, name: "initiating" }, { _id: 1, name: "evaluating" }, { _id: 2, name: "servicing" }, ] let selected = services.findIndex(service => service.name == "evaluating") console.log(selected) 

 let services = [{ _id: 0, name: "initiating" }, { _id: 1, name: "evaluating" }, { _id: 2, name: "servicing" }, ]; let index = services.findIndex(item => item.name === "evaluating"); document.write(index); 

This will return the index after searching through the each object's name property and comparing it to "evaluating". 在搜索每个对象的name属性并将其与“ evaluating”进行比较之后,它将返回索引。

You may use .reduce() : 您可以使用.reduce()

 var services = [ { _id: '<ObjectId>', name: "initiating" }, { _id: '<ObjectId>', name: "evaluating" }, { _id: '<ObjectId>', name: "servicing" }, ]; var idx = services.reduce((x, ele, idx) => (ele.name=='evaluating') ? idx : x, -1); console.log(idx); 

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

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