0

How do I find/match a string in an array?

How can I search within this?
enter image description here

If for example the likes[3].id was "99999" and that was what I wanted to search for... How could I do this??

I tried this:

var likes = response.data
jQuery.inArray(99999, likes)

But without any luck...

Thank you in advance.

curly_brackets
  • 5,491
  • 15
  • 58
  • 102

2 Answers2

2

inArray will only search the top level objects in your array, as you need to find the value of a property on an object you'd need to do something like (not tested) -

var found = false;
var indexFoundAt = -1;
jQuery.each(likes,function(index, value) {
   if (value.id == "99999") {
     found = true;
     indexFoundAt = index;
     return false;  
  }
})
ipr101
  • 24,096
  • 8
  • 59
  • 61
1

If I understood you right, you need to find a string in an array of objects within the id property of each object.

So here's what I suggest

function findId(id_needed)
{
  var found = 0;
  var arrayResult = []
  var likes = [] //your array of objects ofcaurse should be filled some how

  for(var i = 0;i<likes.length;i++)
  {
    if(likes[i].id==id_needed)
    {
      arrayResult[arrayResult.length]=likes[i];
      found +=1;
    }
  }
  return {Found : ((found>0)?(true):(false )),Result : arrayResult}
}

this function will return an object with 2 properties

  1. Found - [true/false]
  2. Result - array of objects with needed ids
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Marwan
  • 2,362
  • 1
  • 20
  • 35