2

I have an Array of Objects in Javascript:

function focal( name, data )
{
    this.name = name;
    this.data = data;
}

count = 0;

arrayFocal = [];
arrayFocal[count] = new focal( "Name", "12/08/2014" );
count++;

Now I want to find into arrayFocal by name
NOTE: IE 8

Lugarini
  • 792
  • 5
  • 11
  • 32
  • I tried inArray, http://stackoverflow.com/questions/5424488/javascript-search-for-a-string-inside-an-array-of-strings , and http://stackoverflow.com/questions/6116474/how-to-find-if-an-array-contains-a-specific-string-in-javascript-jquery – Lugarini Aug 04 '14 at 13:59
  • 1
    `var` is a lovely little thing when you use it ;) And adding to array should be done using `push` would avoid having that count variable. And then the solution is just to use `filter` – GillesC Aug 04 '14 at 14:00

3 Answers3

7

You can use filter

arrayFocal.filter(function(obj){
    return obj.name=='Name';
});

It will return an array of objects which name matched. If you want just first one you can [0] for that.

Mritunjay
  • 25,338
  • 7
  • 55
  • 68
  • Note, however, that this does not work in IE prior to IE 9. If you want older browser support, you'll need to come up with a different solution, or use a third-party library such as underscore.js. – Jason M. Batchelor Aug 04 '14 at 14:04
  • 2
    See this page for an approach to the DIY solution: http://www.devcurry.com/2011/02/filter-array-using-javascript.html You'd then use filter the way @Mritunjay described, above, instead of the `function isEven...` function that they use in that example. – Jason M. Batchelor Aug 04 '14 at 14:11
2

I got the solution:

As @Mritunjay suggested:

You can use filter

arrayFocal.filter(function(obj){
    return obj.name=='Name';
});

But I am using IE 8, and it does not support filter
So we provide an implementation for the filter() method, as @Jason M. Batchelor suggested:
http://www.devcurry.com/2011/02/filter-array-using-javascript.html

Lugarini
  • 792
  • 5
  • 11
  • 32
0

Using underscore

_.findWhere(arrayFocal, {name: name})