8

Not quite grasping what's going on here. Given the array (arr):

[
    {
        "first_name": "Dan",
        "last_name": "Woodson",
        "id": 1
    },
    {
        "first_name": "Jen",
        "last_name": "Woodson",
        "id": 2
    },
    {
        "first_name": "Yoshi",
        "last_name": "Woodson",
        "id": 3
    }
]

And the object (obj):

{
    "first_name": "Yoshi",
    "last_name": "Woodson",
    "id": 3
}

Why would arr.indexOf(obj) return -1 (especially since I retrieved the object from the array using it's 'id' parameter earlier in the function)?

3
  • What do you mean "Earlier in the function" ? You need to show us the code that you wrote which fails, not just some JSON. Commented Dec 23, 2011 at 16:18
  • Can you post the actual code you're using, and/or put it on a fsFiddle? Commented Dec 23, 2011 at 16:19
  • 4
    This is because ({a:12}) === ({a:12}) is false. Objects in JavaScript are equal if they are the same object (same reference), not just the same values. Commented Dec 23, 2011 at 16:20

2 Answers 2

6

Array.indexOf() will only work on objects if the supplied object is exactly the same object you put in.

An exact copy is insufficient, it has to be the exact same object, i.e. there must be some object in the array such that:

arr[i] === obj

You need to show how you retrieved the object.

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

Comments

1

I would like to see the retrieve function, but most likely you are not using the same reference. Because the following is true:

var a = {id: 3};
var b = [a];
b.indexOf(a); // 0
a.id = "not three";
b.indexOf(a); // still 0

However, the following will break:

var a = {id: 3};
var b = [{id: 3}];
b.indexOf(a); // -1 not the same object

Comments

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.