Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);

Is there a way to match objects? For example?

var test = [
    {
        name: 'Josh'
    }
]

// Would ideally return 0, but of course it's -1.
test.indexOf({ name: 'Josh' });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
220 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...