0

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.

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

I assume that by ".all" you mean ".forEach"
@Xotic750: Nope, I meant .every
0

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){...}

2 Comments

Why filter? There's a better iterator function for this task.
@Bergi, This function is suitable when the code will be more difficult - search multiple objects, etc.

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.