indexOf method in an object array?

前端 未结 27 2477
别跟我提以往
别跟我提以往 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:37

    I have made a generic function to check the below is the code & works for any object

    function indexOfExt(list, item) {
        var len = list.length;
    
        for (var i = 0; i < len; i++) {
            var keys = Object.keys(list[i]);
            var flg = true;
            for (var j = 0; j < keys.length; j++) {
                var value = list[i][keys[j]];
                if (item[keys[j]] !== value) {
                    flg = false;
                }
            }
            if (flg == true) {
                return i;
            }
        }
        return -1;
    }
    
    var items = [{ "hello": 'world', "foo": 'bar' }];
    var selectedItem = { "hello": 'world', "foo": 'bar' };
    alert(items.indexOf(selectedItem));
    alert(indexOfExt(items, selectedItem));
    

    The first alert will return -1 (means match not found) & second alert will return 0 (means match found).

提交回复
热议问题