我想遍历元素数组并找到与某些条件匹配的元素的索引号。采取以下数组:
services: [
{ _id: <ObjectId>,
name: "initiating"
},
{ _id: <ObjectId>,
name: "evaluating"
},
{ _id: <ObjectId>,
name: "servicing"
},
]
我将如何遍历此数组,并在属性“名称”等于“求值”的对象(即-数组元素#1)中拉出对象的数组索引号?
答案 0 :(得分:4)
const services = [
{ _id: 1,
name: "initiating"
},
{ _id: 2,
name: "evaluating"
},
{ _id: 3,
name: "servicing"
},
];
console.log(
services.findIndex(({ name }) => name === 'evaluating')
);
答案 1 :(得分:0)
extResult
答案 2 :(得分:0)
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);
这将在搜索每个对象的name属性并将其与“评估”进行比较之后返回索引。
答案 3 :(得分:0)
您可以使用.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);