在对象数组中查找索引

时间:2013-07-18 16:09:39

标签: javascript underscore.js

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

现在我制作了代码来过滤数据并给我回溯对象数据,但没有给出数组索引。

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 个答案:

答案 0 :(得分:11)

使用Lo-Dash代替下划线,您可以使用_.findIndex()轻松完成。

var index = _.findIndex(array, { userid: '7', chid: 'default' })

答案 1 :(得分: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 ) );

答案 2 :(得分:2)

here是帮助你的小提琴希望

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

}

答案 3 :(得分:0)

我不认为你需要下划线只是常规的油脂 - 希望这是你正在寻找的

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