Javascript 根据其属性获取数组元素的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12553274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting index of an array's element based on its properties
提问by Robert Kirsz
I have a JavaScript array of objects like this:
我有一个 JavaScript 对象数组,如下所示:
var myArray = [{...}, {...}, {...}];
Each object has unique id
among other properties:
每个对象id
在其他属性中都是独一无二的:
{
id: 4,
property1: 'something',
property2: 'something'
}
How can I get an index of a particular object in that array, if I only know its id
property? So if I know that myArray[x].id == 4
, how can I find x
?
如果我只知道它的id
属性,如何获得该数组中特定对象的索引?所以,如果我知道,myArray[x].id == 4
我怎么能找到x
?
回答by xdazz
回答by Dmitry Shvedov
Or with ES6 syntax:
或者使用 ES6 语法:
let index = myArray.map( el => el.id ).indexOf(4)
or
或者
let index = myArray.findIndex( el => el.id === 4 )
回答by Denys Séguret
Why not simply make a loop ?
为什么不简单地做一个循环?
function indexOfId(array, id) {
for (var i=0; i<array.length; i++) {
if (array[i].id==id) return i;
}
return -1;
}
The fact that there are many facilities in js (or js libraries) doesn't mean you must not, sometimes, write a loop. That's fast and simple.
js(或 js 库)中有许多工具这一事实并不意味着您有时不能编写循环。这既快速又简单。
回答by yar1
const myArray = [{id:1}, {id:2}, {id3}];
const foundIndex = myArray.findIndex((el) => (el.id === 3));
回答by I Hate Lazy
You can use .reduce()
, which lets you reduce an Array down to a single value.
您可以使用.reduce()
,它可以让您将 Array 减少到单个值。
var obj_idx = myArray.reduce(function(idx, item, i) {
return item.id === 4 ? i : idx;
}, -1);
The -1
is a default value if no match is found.
的-1
,如果没有找到匹配的是默认值。
If you have multiple uses for this, you may want to make a function factory.
如果您对此有多种用途,您可能需要创建一个函数工厂。
function idxForID(target) {
return function(idx, item, i) {
return item.id === target ? i : idx;
};
}
And then use it like this.
然后像这样使用它。
var obj_idx = myArray.reduce(idxForID(4), -1);
回答by Marcus
If each id is unique, you can do it like this:
如果每个 id 都是唯一的,您可以这样做:
o1 = {id:1}
o2 = {id:2}
o3 = {id:3}
o4 = {id:4}
a = [o1,o2,o3,o4]
a.indexOf( a.filter( function(i){return i.id==4} )[0] );
回答by jeremy
You could also try a recursive function, though @xdazz's looks rather attractive.
您也可以尝试使用递归函数,尽管 @xdazz 看起来很有吸引力。
var indexOfId = function(arr, id, index) {
if (!index) { index = 0; }
if (arr[index].id == id) {
return index;
}
return ((index += 1) >= arr.length) ? -1 : indexOfId(arr, id, index);
};