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.

3
  • did you also tried jQuery.inArray("99999", likes) Commented Oct 26, 2011 at 14:11
  • likes appears to be a json object not an array. Commented Oct 26, 2011 at 14:11
  • This might help stackoverflow.com/questions/4992383/… Commented Oct 26, 2011 at 14:13

2 Answers 2

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;  
  }
})
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.