KLôN KLôN - 4 months ago 12
Node.js Question

How can I find the index of an object having a specific value in an array?

Since the title is not easy to get, I'll provide an example :



var myObject =
{ "myArray" :
[
{"hashKey": "someHashkey1",
"data": "someData1"
},
{"hashKey": "someHashkey2",
"data": "someData2"
},
{"hashKey": "someHashkey3",
"data": "someData3"
}
]
};





I have "myObject" containing "myArray", and now I would like to efficiently find the index of the object having, for instance, the hashKey "someHashKey2".

I could build my own loop to check all elements in the array, but :


  1. is there a built-in way to do it ? Something like indexOf() ?

  2. is there a npm tool for that kind of need (I work in Node.js)

  3. is there an efficient way to work here ? some bad way to avoid ?



[EDIT :]
My efficiency question is due to the fact that I will have to do this operation for basically all the hashKeys. I just found this question which has a "lookup" answer that could help. Still in the process of understanding it all...

Answer

If you have an hash key I would recommend you to convert the array to an object and then you could find the object using the hash key like this: myObject.myArray["someHashkey1"]

var myObject = 
    { "myArray" : 
       {
         "someHashkey1":{
          "hashKey": "someHashkey1",
          "data": "someData1"
         },
         "someHashkey2":{
          "hashKey": "someHashkey2",
          "data": "someData2"
         }
       }
     };
     console.log(myObject.myArray["someHashkey1"]);