Find index in array of objects

后端 未结 4 2181
梦如初夏
梦如初夏 2021-01-18 15:54

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 i

4条回答
  •  自闭症患者
    2021-01-18 16:12

    I don't think you need underscore for that just regular ole js - hope this is what you are looking for

    var data =  [
            {
                "text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
            },
            {
                "text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
            }
        ];
    
    var userid = "userid"
    var filterparams = {userid:'7', chid: 'default'};
    var index;
    for (i=0; i < data.length; i++) {
        for (prop in data[i]) {
            if ((prop === userid) && (data[i]['userid'] === filterparams.userid)) {
                index = i
            }
        }
    }
    
    alert(index);
    

提交回复
热议问题