Manju Kb
Manju Kb

Reputation: 55

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; object

tried this x.indexOfKey(false, "_id") but returns -1 and this works fine x.indexOfKey(true, "_id")

What am i doing wrong??

Upvotes: 3

Views: 162

Answers (3)

KrishCdbry
KrishCdbry

Reputation: 1059

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.

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

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

Here is the working live example : https://jsbin.com/nukitam/2/edit?js,console

Hope this helps ! Thanks

Upvotes: 1

Samuel Toh
Samuel Toh

Reputation: 19298

Use the standard array.findIndex API.

See:
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; }));

Upvotes: 2

WalksAway
WalksAway

Reputation: 2829

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

Upvotes: 0

Related Questions