过滤数组基于在javascript中过滤具有多个数组的另一个对象

时间:2017-01-13 13:15:33

标签: javascript

我有一个对象数组。我想基于对象具有条件来过滤数组。

我的数组如下:

var data = [
{
  "name": "nitin",
  "r_id": "1",
  "t_id": "4"
},
{
 "name": "test",
  "r_id": "2",
  "t_id": "3"
},
{
  "name": "test1",
  "r_id": "2",
  "t_id": "4"
},
{
  "name": "test3",
  "r_id": "3",
  "t_id": "3"
},
{
  "name": "test2",
  "r_id": "1",
  "t_id": "1"
}]

我的目标如下:

var obj = {
role:['1','2'],
type:['1','3']
}

其中r_id是角色id,t_id是类型id

所以我希望角色id为1或2的结果AND类型id为1或3。

如此数学上的role_id&& type_id((1 || 2)&&(1 || 3))

我的输出应该是:

var result = [
{
  'name':'test',
  'r_id':2,
  't_id':3,
},
{
  'name':'test2',
  'r_id':1,
  't_id':1,
}];

4 个答案:

答案 0 :(得分:1)

var data = [
{
  "name": "nitin",
  "r_id": "1",
  "t_id": "4"
},
{
 "name": "test",
  "r_id": "2",
  "t_id": "3"
},
{
  "name": "test1",
  "r_id": "2",
  "t_id": "4"
},
{
  "name": "test3",
  "r_id": "3",
  "t_id": "3"
},
{
  "name": "test2",
  "r_id": "1",
  "t_id": "1"
}]

var obj = {
role:['1','2'],
type:['1','3']
}

let result = data.filter(item=>{
	return obj.role.indexOf(item.r_id) > -1 && obj.type.indexOf(item.t_id) > -1
})

console.log(result)

答案 1 :(得分:0)

您只需要迭代data,看看r_id(在各自的数组中)是否存在密钥(t_idobj)。为此,您可以使用Array.filter

var data = [{"name":"nitin","r_id":"1","t_id":"4"},{"name":"test","r_id":"2","t_id":"3"},{"name":"test1","r_id":"2","t_id":"4"},{"name":"test3","r_id":"3","t_id":"3"},{"name":"test2","r_id":"1","t_id":"1"}]

var obj = {
  role:['1','2'],
  type:['1','3']
}

var result = data.filter(function(element){
    return obj.role.indexOf(element.r_id) !== -1 && // element has valid role
           obj.type.indexOf(element.t_id) !== -1 // element has valid type
})

console.log(result)

答案 2 :(得分:0)



var data = [
{
  "name": "nitin",
  "r_id": "1",
  "t_id": "4"
},
{
 "name": "test",
  "r_id": "2",
  "t_id": "3"
},
{
  "name": "test1",
  "r_id": "2",
  "t_id": "4"
},
{
  "name": "test3",
  "r_id": "3",
  "t_id": "3"
},
{
  "name": "test2",
  "r_id": "1",
  "t_id": "1"
}]

var obj = {
role:['1','2'],
type:['1','3']
}

var filterItems = data.filter(function(o){ 
   return obj.role.indexOf(o.r_id) != -1  && obj.type.indexOf(o.t_id) != -1; });

console.log(filterItems);




答案 3 :(得分:0)

您可以更改% tile(T) holds for all identifier used in adj/2 atoms. tile(T):- adj(T,_). tile(T):- adj(_,T). % yield between m and n mines (with m=0 and n=2) 0 {mine(F): tile(F)} 2. 一点,对于您拥有的数据中的相应属性名称,然后使用Array#filter并使用Array#every检查所需项目。



obj

var data = [{ name: "nitin", r_id: "1", t_id: "4" }, { name: "test", r_id: "2", t_id: "3" }, { name: "test1", r_id: "2", t_id: "4" }, { name: "test3", r_id: "3", t_id: "3" }, { name: "test2", r_id: "1", t_id: "1" }],
    obj = { r_id: ['1', '2'], t_id: ['1', '3'] },
    keys = Object.keys(obj),
    result = data.filter(function (o) {
        return keys.every(function (k) {
            return obj[k].indexOf(o[k]) !== -1;
        });
    });

console.log(result);