0

I have an array of objects in javascript. The objects contain some properties and look something like this :

  { "Name" : "blabla", "Id": "1" }

Now I have a function which accepts a single parameter that will be the Name property value of the object. The function looks somethings like this :

     function CheckForExistance(array, name){
       var exist = false;

       $.each(array, function(index, value){
          if(value.Name == name)
          {
             exist = true;
             return false;
          }
       });
       return exist;
     }

I want to know if there is a better way to do this ?

ColBeseder
  • 3,579
  • 3
  • 28
  • 45
user1740381
  • 2,121
  • 8
  • 37
  • 61
  • You might find an answer here: http://stackoverflow.com/questions/3975871/optimize-search-through-large-js-string-array – salih0vicX Oct 28 '12 at 17:14
  • 1
    If the `Name` serves as the unique identifier for the object then you should use it directly as the member name within the object and then access the values directly without a search at all. – Matt Whipple Oct 28 '12 at 17:17
  • Maybe his array is only an example of what he wants to achieve with his function. – Angelo A Oct 28 '12 at 17:22
  • possible duplicate of [Find object by id in array of javascript objects](http://stackoverflow.com/questions/7364150/find-object-by-id-in-array-of-javascript-objects) -- please use the search before you ask a new question. – Felix Kling Oct 28 '12 at 17:56

4 Answers4

4

You can use $.grep() to filter down the array to a match, and return a comparison of the .length.

 function CheckForExistance(array, name){
     return $.grep(array, function(obj) {
         return obj.Name == name;
     }).length > 0;
 }

Or native methods are a little nicer IMO, but you'll need a shim for old browsers.

function CheckForExistance(array, name){
    return array.some(function(obj) {
        return obj.Name == name;
    });
}

This one uses Array.prototype.some, and will exit as soon as a truthy return value is given, and will then return true. If no truthy return is found, then it'll return false.


FWIW, you can make your function a little more robust by providing a dynamic property name as well.

function CheckForExistance(array, prop, val){
    return array.some(function(obj) {
        return obj[prop] == val;
    });
}

Then use it to check any property value.

var found = CheckForExistance(myArray, "Name", "blabla");

Or another approach would be to make a function factory that creates functions to be used with iterators.

function havePropValue(prop, value) {
    return function(obj) {
        return obj[prop] == value;
    };
}

Then we can just use .some() directly without needing the CheckForExistance function.

var found = myArray.some(havePropValue("Name", "blabla"));

Or with $.grep.

var found = $.grep(myArray, havePropValue("Name", "blabla")).length > 0;
I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
2

If it is a simple array object why not just loop through it, instead of complicating it why to use $.each when plain JavaScript is simpler

 function CheckForExistance(array, name) {
   for(var i=0;i<array.length;i++){
     if(array[i].Name==name) return true;
   }
   return false;
 }
Anurag Uniyal
  • 85,954
  • 40
  • 175
  • 219
  • There is no simple dict object - it's an array of object literals – Ian Oct 28 '12 at 17:30
  • @ianpgall what nonsense OP has `{ "Name" : "blabla", "Id": "1" }` why it wouldn't work? – Anurag Uniyal Oct 28 '12 at 17:30
  • Please read the actual question. "I have an array of objects in javascript." The sentence after describes the structure of each object. The OP has code that works, but they are wondering if there's a "better" way to do it. Your simplification of how to loop over an object doesn't improve or help the OP with their array of objects... – Ian Oct 28 '12 at 17:32
  • 1
    You're not stupid at all, the original question is worded weird. I just want to make sure the OP gets an answer that is what they need, so that's why I explained – Ian Oct 28 '12 at 17:33
0

You could also use the native Array.fiter method to determine whether the object with Name x does exist or not. Filter returns a new array, containing all the elements, which are matching the callback function (return true). https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter

If the length of the new array is greater than 0, than there is at least one matching element.

function checkForExistance(arrayOfItems, name) {
    return arrayOfItems.filter(function (item) {
        return item.Name === name;
    }).length > 0;

}


var arr = [{
    "Name": "blabla",
    "Id": "1"
}, {
    "Name": "foo",
    "Id": "2"
}]

console.log(checkForExistance(arr, "foo"));

http://jsfiddle.net/Uawrb/1/

This won't work in IE<9, but if you want it to work there too, you can check out jQuery's $.grep implementation, which should work cross-browser :)

function checkForExistance(arrayOfItems, name) {
    return $.grep(arrayOfItems, function (item) {
        return item.Name === name;
    }).length > 0;

}


var arr = [{
    "Name": "blabla",
    "Id": "1"
}, {
    "Name": "foo",
    "Id": "2"
}]

console.log(checkForExistance(arr, "foo"));​

http://jsfiddle.net/5vqqq/1/

Robin Drexler
  • 4,307
  • 3
  • 25
  • 28
-1

This should work:

function CheckForExistance(array, name){
           var exist = false;
           $.each(array, function(index, value){
              if (value == name) {
                   exist = true;
              }
           });
           return exist;
         }

value.Name isn't a string. When looping trough an array you get an index and a value.

For example: array { 1: "foo", 2:"bar" } gives you index: 1, value: "foo" index: 2, value: "bar"

value is the one you want to compare to your variable 'name'.

2: You returned false after making 'exist' true. That will never give a 'return true'. After making 'exist' true you should return exist.

I think my code is what you're looking for.

Angelo A
  • 2,744
  • 6
  • 28
  • 37
  • thanks for reply, but `return false` is for breaking the each loop if i found the object – user1740381 Oct 28 '12 at 17:23
  • 1
    I didn't vote, but your code won't work. It'll always return `false`. The `return true` is in the `$.each` callback, and will be ignored. – I Hate Lazy Oct 28 '12 at 17:31
  • 1
    Yes now it should work, but it's **almost** exactly the same as the OP's code, but is less efficient. Using `return false` inside of the `$.each` callback breaks the loop - which is what **should** be done so that extra processing is not done on the rest of the array if the item matches sooner. – Ian Oct 28 '12 at 17:39
  • Didn't realise that. Thought when you return false inside the array, the whole function returnes false. Thanks for the information. – Angelo A Oct 28 '12 at 17:40
  • 1
    That's what I would think too, but it gets a little weird with jQuery methods - since it's a callback, normal `return` statements don't always mean what you want (and this is a perfect example). But in a normal Javascript `for` loop, if you use `return`, it will do what you're expecting, and leave the function. – Ian Oct 28 '12 at 17:42