0

I am having array objects in jquery in which has n number of items

array={id:1, name:x};
array={id:2, name:y};
array={id:3, name:z};
.
.
.
.
array={id:n, name:n};

Now I have to find particular item in this array object since i dont know the index of item.

if(array.id==item)
{
// change array.name=somename;
}
else
{
//add new value into array
array.push({id=item,name=somename});
}

Without using index of an item do i have any option in foreach or any other method to find an item in jquery?

Kalaivani
  • 477
  • 3
  • 9
  • 17
  • This may help http://api.jquery.com/jQuery.inArray/ – DaiYoukai Feb 17 '12 at 06:29
  • You should accept one of the answers so that people that went to the effort to help can be awarded their points. You accept by clicking on one of the check marks displayed beside each answer. – DG. Mar 03 '12 at 04:53

3 Answers3

0

You can change your array so that it acts more like a dictionary. That way you don't have to search through the entire array, but just do a single lookup.

dictionary = {};
dictionary[1] = {name:x};
dictionary[2] = {name:y};
...
dictionary[id] = {name:somename};

Now you don't have to check if the id exists or not, as it will replace it if it exists, and create a new one if it doesn't. If you would like to check if it exists, just use the typeof method and check if it's undefined.

Rob Taylor
  • 604
  • 4
  • 10
0

This may answer your question: Leveraging JQuery find or inArray method to find an item in an array

Read the comments on the first answer.

Community
  • 1
  • 1
DG.
  • 3,417
  • 2
  • 23
  • 28
0

inArray method only matches the exact object so if the objects are identical then you can use it like;

if(jQuery.inArray({id: item,name: somename})!=-1)
 array.push({id: item,name: somename});

but if you only want to check id, you can use grep to select object mathcing with id like:

if(jQuery.grep( array, function(a){return a.id==item}).length ==1)
 array.push({id: item,name: somename});
Naren Sisodiya
  • 7,158
  • 2
  • 24
  • 35
  • 1
    if(jQuery.grep( array, function(a){return a.id==item}).length ==1){//have to change that a.name into somename } else{push:id, name:somename} How can i replace the name of that particular id if exists? – Kalaivani Feb 17 '12 at 08:31