Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

javascript - array indexOf with objects?

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...