plrthink
plrthink

Reputation: 311

how to determine if an object is in an array only with a property in javascript?

I have an array of object, and every object has a property named 'done', and other properties. what i want to do is determine whether an object is in that array only by comparing properties except 'done' property.

it works this:

var my_array = [ 
                {'done': false, 'name': 'do homework'}, 
                {'done': true, 'name': 'buy some food'}
               ];
var my_object = {'done': true, 'name': 'do homework'};
if(someFunction(my_arry, my_object)){
  window.alret('called');
}

and I want it display 'called'.

is there some way I can do that? Please help me.

Upvotes: 0

Views: 84

Answers (2)

Eric
Eric

Reputation: 97571

Here's a way to find an object in your array with a matching name:

if(my_array.some(function(x) { return x.name == my_object.name; })) {
    alert("called")
}

If you want to compare all properties:

if(my_array.some(function(x) {
    return Object.keys(x).every(function(k) {
        return k == 'done' || x[k] == my_object[k];
    });
})) {
    alert("called")
}

Although that's sort of pushing our luck with the length of the expression in the if statement, and would be easier to read with things pulled out into functions

Upvotes: 3

3y3
3y3

Reputation: 802

This is simple example with Array.filter:

var my_array = ...;
var my_object = ...;

var done = my_array.filter(function(e){
  for(var opt in my_object) {
    if(opt != 'done') if(!e[opt]||!e[opt]!=my_object[opt]) return false;
  }
  return true;
})
if(done.length){...}

Upvotes: 0

Related Questions