Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find index in array of objects

I would like to find index in array. Positions in array are objects, and I want to filter on their properties. I know which keys I want to filter and their values. Problem is to get index of array which meets the criteria.

For now I made code to filter data and gives me back object data, but not index of array.

var data =  [
        {
            "text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
        },
        {
            "text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
        }
    ];

var filterparams = {userid:'7', chid: 'default'};

function getIndexOfArray(thelist, props){
    var pnames = _.keys(props)
    return _.find(thelist, function(obj){
        return _.all(pnames, function(pname){return obj[pname] == props[pname]})
    })};

var check = getIndexOfArray(data, filterparams ); // Want to get '2', not key => val
like image 514
norbert Avatar asked Jul 18 '13 16:07

norbert


1 Answers

Using Lo-Dash in place of underscore you can do it pretty easily with _.findIndex().

var index = _.findIndex(array, { userid: '7', chid: 'default' })
like image 67
idbehold Avatar answered Sep 25 '22 03:09

idbehold