5

我想在数组中找到索引。数组中的位置是对象,我想过滤它们的属性。我知道要过滤哪些键及其值。问题是获得符合条件的数组索引。

现在我编写了代码来过滤数据并返回对象数据,但不返回数组索引。

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
4

4 回答 4

11

使用Lo-Dash代替下划线,您可以使用_.findIndex().

var index = _.findIndex(array, { userid: '7', chid: 'default' })
于 2013-07-18T17:27:28.800 回答
2

我不确定,但我认为这是你需要的:

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'};

var index = data.indexOf( _.findWhere( data, filterparams ) );
于 2013-07-18T16:35:21.230 回答
2

是小提琴希望它可以帮助你

 for(var intIndex=0;intIndex < data.length; intIndex++){
  eachobj = data[intIndex];
var flag = true;
 for (var k in filterparams) {

    if (eachobj.hasOwnProperty(k)) {
        if(eachobj[k].toString() != filterparams[k].toString()){
           flag = false;
        }
    }
}
if(flag){
       alert(intIndex);
}

}

于 2013-07-18T16:38:48.200 回答
0

我认为您不需要下划线来处理常规的 ole js - 希望这就是您正在寻找的

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);
于 2013-07-18T16:30:39.950 回答