array indexOf with objects?

前端 未结 3 1575
情书的邮戳
情书的邮戳 2020-12-21 18:10

I know we can match array values with indexOf in JavaScript. If it matches it wont return -1.

var test = [
    1, 2, 3
]

// Returns 2
test.indexOf(3);
         


        
3条回答
  •  死守一世寂寞
    2020-12-21 18:48

    Since the two objects are distinct (though perhaps equivalent), you can't use indexOf.

    You can use findIndex with a callback, and handle the matching based on the properties you want. For instance, to match on all enumerable props:

    var target = {name: 'Josh'};
    var targetKeys = Object.keys(target);
    var index = test.findIndex(function(entry) {
        var keys = Object.keys(entry);
        return keys.length == targetKeys.length && keys.every(function(key) {
            return target.hasOwnProperty(key) && entry[key] === target[key];
        });
    });
    

    Example:

    var test = [
        {
            name: 'Josh'
        }
    ];
    
    var target = {name: 'Josh'};
    var targetKeys = Object.keys(target);
    var index = test.findIndex(function(entry) {
        var keys = Object.keys(entry);
        return keys.length == targetKeys.length && keys.every(function(key) {
            return target.hasOwnProperty(key) && entry[key] === target[key];
        });
    });
    console.log(index);

    Note that findIndex was added in ES2015, but is fully polyfillable.

提交回复
热议问题