indexOf method in an object array?

前端 未结 27 2437
别跟我提以往
别跟我提以往 2020-11-22 02:18

What\'s the best method to get the index of an array which contains objects?

Imagine this scenario:

var hello = {
    hello: \'world\',
    foo: \'ba         


        
27条回答
  •  礼貌的吻别
    2020-11-22 02:52

    var hello = {hello: "world",  foo: "bar"};
    var qaz = {hello: "stevie", foo: "baz"};
    var myArray = [];
    myArray.push(hello,qaz);
    
    function indexOfObject( arr, key, value   ) {
        var j = -1;
        var result = arr.some(function(obj, i) { 
            j++;
            return obj[key] == value;
        })
    
        if (!result) {
            return -1;
        } else {
            return j;
        };
    }
    
    alert(indexOfObject(myArray,"hello","world"));
    

提交回复
热议问题