简体   繁体   English

javascripts indexOfKey如何工作

[英]How javascripts indexOfKey works

I have an array object like this 我有一个像这样的数组对象

 var x =  [{"_id":null,"count":7},{"_id":false,"count":362},     {"_id":true,"count":926}]

How to take index of _id = false; 如何获取_id = false的索引; object 宾语

tried this x.indexOfKey(false, "_id") but returns -1 and this works fine x.indexOfKey(true, "_id") 尝试了这个x.indexOfKey(false, "_id")但返回-1,这很好用x.indexOfKey(true, "_id")

What am i doing wrong?? 我究竟做错了什么??

Use the standard array.findIndex API. 使用标准的array.findIndex API。

See: 看到:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

 var x = [{"_id":null,"count":7},{"_id":false,"count":362}, {"_id":true,"count":926}]; console.log("Index of _id==false is: " + x.findIndex((element) => { return element._id == false; })); 

var array =  [{"_id":null,"count":7},{"_id":false,"count":362},{"_id":true,"count":926}];
var idx = -1;
array.filter(function(val, key) {
    if (val['_id'] === false) {
        idx = key;
     }
 });

Now the idx will have the index value of that particular object which is having key _id as false in above array. 现在,idx将具有该特定对象的索引值,该索引值在上面的数组中具有键_idfalse

console.log(idx); // 1

If we want multiple indexes of same key value then we can go with array 如果我们想要具有相同键值的多个索引,那么我们可以使用数组

var array2 = [{"_id":null,"count":7},{"_id":false,"count":362},{"_id":true,"count":926}, {"_id":false,"count":462}];
var idxs = [];
array2.filter(function(val, key) {
   if (val['_id'] === false) {
        idxs.push(key);
    }
 });

This will track and push all the idexes of object into idxs array whose is having _id as false in above array2 这将跟踪并将对象的所有idex推入idxs数组, 数组在上面的array2中具有_id为false

console.log(idxs);   // [1,3]

Here is the working live example : https://jsbin.com/nukitam/2/edit?js,console 以下是工作实例: https//jsbin.com/nukitam/2/edit?js,console

Hope this helps ! 希望这可以帮助 ! Thanks 谢谢

to get the index from an array of objects using a property you can use this: 要使用属性从对象数组中获取索引,您可以使用:

 var x = [{ "_id": null, "count": 7 }, { "_id": false, "count": 362 }, { "_id": true, "count": 926 }] var index = x.map(function(e) { return e._id; }).indexOf(true); console.log(index); 

map the property into an array and then use indexOf https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf 将属性映射到数组,然后使用indexOf https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

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

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