0

I want to find out which index(es) in the following array contains an object whose value for the key "id" is x.

var arr1 = [
  {
    "id":42,
    "name":"Object 42"
  },
  {
    "id":99,
    "name":"Object 99"
  }
]

So for that array, I would want to do this;

findId(arr, 42);
//returns '0'
findId(arr, 99);
//returns '1'

How can I write a function that does that?

This is different than the supposed duplicates, because those duplicates talk about filtering a simple array for a certain value. This question is trying to filter an array of objects where a certain key has a value of x. None of the duplicates solve the problem.

Jo Sprague
  • 16,523
  • 10
  • 42
  • 62
  • 3
    What have you tried? See here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter – elclanrs Jul 31 '14 at 20:23
  • More related http://stackoverflow.com/questions/13594788/javascript-filter-array-of-objects, http://stackoverflow.com/questions/2722159/javascript-how-to-filter-object-array-based-on-attributes – elclanrs Jul 31 '14 at 20:26
  • I tried Array.prototype.filter, but that doesn't allow me to filter based on the value of the `id` property of the objects within the array. – Jo Sprague Aug 01 '14 at 14:23
  • @JosiahSprague: How so? – Lightness Races in Orbit Aug 01 '14 at 14:47

0 Answers0