How can I find the index of an object inside a Array using underscore.js?

前端 未结 7 792
滥情空心
滥情空心 2021-02-14 07:45

I want to get the index of the given value inside a Array using underscore.js.

Here is my case

var array = [{\'id\': 1, \'name\': \'xxx\'},
                      


        
7条回答
  •  失恋的感觉
    2021-02-14 08:33

    With objects, === and == check to see if two references refer to the same object; it doesn't check for equivalent objects:

    var a = {foo: "bar"};
    var b = {foo: "bar"};
    console.log(a === b); // false, `a` and `b` refer to different (but equivalent) objects
    a = b = {something: "here"};
    console.log(a === b); // true, `a` and `b` refer to the *same* object
    

    You have to test the object's properties to make the decision. In your case, the id property looks like a good option, or if you want to compare all of the properties, you might use Underscore's isEqual.

提交回复
热议问题