indexOf method in an object array?

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

    While, most other answers here are valid. Sometimes, it's best to just make a short simple function near where you will use it.

    // indexOf wrapper for the list of objects
    function indexOfbyKey(obj_list, key, value) {
        for (index in obj_list) {
            if (obj_list[index][key] === value) return index;
        }
        return -1;
    }
    // Find the string in the list (default -1)
    var test1 = indexOfbyKey(object_list, 'name', 'Stevie');
    var test2 = indexOfbyKey(object_list, 'last_name', 'some other name');
    

    It depends on what is important to you. It might save lines of code and be very clever to use a one-liner, or to put a generic solution somewhere that covers various edge cases. But sometimes it's better to just say: "here I did it like this" rather than leave future developers to have extra reverse engineering work. Especially if you consider yourself "a newbie" like in your question.

提交回复
热议问题