0

I have an array arr1, which contains all objects.

var arr1 = [{name:"haha1"},{name:"haha2"}] 

I also have an object.

var a1 = {name:"haha1"}; 

So, how do I determine whether a1 is equal to any of the objects in arr1? I tried == but it doesn't check if the properties of the objects are equal.

3
  • 1
    You want to check if an object with values identical to that of a1 exists in the array? Commented Nov 15, 2015 at 10:24
  • 1
    You need to loop through the array, and check if the name of each object is equal to the name of a1. Commented Nov 15, 2015 at 10:24
  • 1
    Hi, your question is a bit confusing. The arr1 is an array of objects and the a1 is an object. What do you want? Do you want to see if a1 is contained in arr1, meaning that there is an object with the same value for the name property? Commented Nov 15, 2015 at 10:24

2 Answers 2

2

Just loop through the array, and compare each object in it to a1.

var arr1 = [{name:"haha1"},{name:"haha2"}] var a1 = {name:"haha1"}; function objectsEqual(obj1, obj2) { var equal = obj1.name === obj2.name; return equal; } var i; for(i = 0; i < arr1.length; i++) { if(objectsEqual(a1, arr1[i])) { console.log('a1 is equal to object at index ' + i); } }

I created a function to check for equality, because you may have more properties to check in your real code. So, you can check them all in that function, and re-use that function in other places, if you need to.

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

Comments

0

You can use underscore library.

var arr1 = [{name:"haha1"},{name:"haha2"}] var a1 = {name:"haha1"}; var isContainsObj = function (arr, obj) { return _.where(arr1, a1).length > 0 } console.log(isContainsObj(arr1, a1)) //true 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.