简体   繁体   English

javascript在对象数组中查找匹配值的索引

[英]javascript find index of matched value in ay array of objects

I'm looking for the index of an item in an array of a list of objects by looking for a specific value inside of an object 我正在通过在对象内部查找特定值来在对象列表数组中查找项目的索引

currently, I'm doing this via 目前,我正在通过

var x = [{ _id: '59974d9015a07e09b88e3b53', status: '1', id: '59974d2915a07e09b88e3b4b' }, { _id: '12345', status: '1', id: '54321' }]

var index = null;

for (var i=0; i<x.length; i++) {
    if ( x[i]._id == '59974d9015a07e09b88e3b53' ) {
        index = i;
        break;
    }
}

https://jsfiddle.net/yaocpsjd/ https://jsfiddle.net/yaocpsjd/

is there a more elegant solution via ES* where I wouldn't need to do a loop? 是否有不需要ES *的更优雅的解决方案?

You can use findIndex() method that returns index of first element that satisfies condition otherwise it returns -1. 您可以使用findIndex()方法返回满足条件的第一个元素的索引,否则返回-1。

 var x = [{ _id: '59974d9015a07e09b88e3b53', status: '1', id: '59974d2915a07e09b88e3b4b' }, { _id: '12345', status: '1', id: '54321' }] var index = x.findIndex(e => e._id == '59974d9015a07e09b88e3b53') console.log(index) 

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

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