在对象数组中查找索引 [英] Find index in array of objects

查看:65
本文介绍了在对象数组中查找索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

此处是小提琴家希望它帮助您

here is thefiddle hope it helps you

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

}

这篇关于在对象数组中查找索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆