[英]How can I find out the array position of an object by searching the array?
If I have an array like this: 如果我有这样的数组:
var array1 =
[
{"phraseId":"abc",
"keyword":"bb",
"posId":1},
{"phraseId":"def",
"keyword":"bb",
"posId":1},
]
How can I find out that the object with phraseId of "def" has the 2nd position? 我怎么能找到具有“ def”的词组标识的对象处于第二位置?
您可以映射对象,仅返回目标字段,然后使用内置的indexOf
获取位置:
array1.map(item => item.phraseId).indexOf('def')
Use native JavaScript findIndex
method. 使用本机JavaScript findIndex
方法。
var array1 = [{ "phraseId": "abc", "keyword": "bb", "posId": 1 }, { "phraseId": "def", "keyword": "bb", "posId": 1 }, ]; var pos = array1.findIndex(function(v) { // set your condition for finding object return v.phraseId == 'def'; // add `1` since you want to count from `1` }) + 1; console.log("Position of the object " + pos);
For older browser check polyfill option . 对于较旧的浏览器, 请检查polyfill选项 。
With ES6 arrow function 具有ES6箭头功能
var array1 = [{ "phraseId": "abc", "keyword": "bb", "posId": 1 }, { "phraseId": "def", "keyword": "bb", "posId": 1 }, ]; var pos = array1.findIndex(v => v.phraseId == 'def') + 1; console.log("Position of the object " + pos);
It works this way : 它是这样工作的:
array1.forEach((elem, index) => {if (elem.phraseId === "def")
console.log("index = " + index);
});
Assuming that your key is know (that you know you are looking for a phraseId
always) then you can simply iterate through the array with a normal for
loop if you are using "traditional" JS, or with a forEach
if you are using ES6. 假设您的密钥是已知的(您知道您一直在寻找phraseId
),那么如果使用“传统” JS,则可以使用普通的for
循环简单地遍历数组,如果使用ES6,则可以使用forEach
进行遍历。 Here's the simple for
implementation. 这是实现的简单for
。
for (var i = 0; i < array1.length; i++ ){
if(array[i].phraseId === 'def') {
// we know "i" is the index, so do something...
}
}
To make it more generic so you can search any array for any key, make a function of it that returns the index: 为了使其更通用,以便您可以在任何数组中搜索任何键,请为其创建返回索引的函数:
function whatIndex (arr, key, val) {
for (var i = 0; i < arr.length; i++) {
if( arr[i][key] === val ) {
return i;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.