使用多个属性过滤多个数组对象

时间:2018-05-30 03:23:21

标签: javascript typescript underscore.js lodash

我试图创建一个过滤器函数,它可以从给定的字符串键集返回与我要查找的值匹配的数据结果

数组示例:

let data = [
 { id:1 , data:{ name:"sample1",address:{ cat:"business" } } },
 { id:2 , data:{ name:"sample2",address:{ cat:"office"  }  } },
 { id:3 , data:{ name:"sample3",address:{ cat:"office"  } } },
 { id:4 , data:{ name:"sample4",address:{ cat:"office"  }  } }
 { id:5 , data:{ name:"sample5",address:{ cat:"home"  } } }
 { id:6 , data:{ name:"sample6",address:{ cat:"home"  }  } }
]



function filter( collection , value ,key ){
  //code 
}


let result = filter( data , "business" , [ "data","address","cat" ] )

console.log(result)

预期结果是

  

{id:1,data:{name:“sample1”,地址:{cat:“business”}}},

3 个答案:

答案 0 :(得分:4)

您可以使用filter搜索数据。使用reduce构建密钥。

注意:filter返回匹配元素的数组。如果您只想要第一场比赛,可以使用find

let data = [
  { id:1 , data:{ name:"sample1",address:{ cat:"business" } } },
  { id:2 , data:{ name:"sample2",address:{ cat:"office"  }  } },
  { id:3 , data:{ name:"sample3",address:{ cat:"office"  } } },
  { id:4 , data:{ name:"sample4",address:{ cat:"office"  }  } },
  { id:5 , data:{ name:"sample5",address:{ cat:"home"  } } },
  { id:6 , data:{ name:"sample6",address:{ cat:"home"  }  } }
];


function filter(collection, value, key) {
  return collection.filter(o => key.reduce((c, v) => c[v] || {}, o) === value);
}

let result = filter(data, "business", ["data", "address", "cat"])

console.log(result)

答案 1 :(得分:1)

function filter( collection , value ,key ){
  const getNestedObjectValue = (nestedObject, propertyPath) => {
      return propertyPath.reduce((obj, key) =>
          (obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObject);

  };
  return collection.filter( item => getNestedObjectValue(item, key) === value);
}

当匹配时,filter函数将返回匹配对象的数组,当没有匹配时,将返回空数组

let result = filter( data , "business" , [ "data","address","cat" ] );

console.log(result); // [{"id":1,"data":{"name":"sample1","address":{"cat":"business"}}}]

let result2 = filter( data , "office" , [ "data","address","cat" ] );

console.log(result2); //[{"id":2,"data":{"name":"sample2","address":{"cat":"office"}}},{"id":3,"data":{"name":"sample3","address":{"cat":"office"}}},{"id":4,"data":{"name":"sample4","address":{"cat":"office"}}}]

let result3 = filter( data , "vacation" , [ "data","address","cat" ] );

console.log(result2); // [] 

答案 2 :(得分:0)

您可以尝试以下代码。

  

如果不能解决您的问题,或者您希望在代码中添加更多功能,请发表评论。我会更新我的答案。

function filter( collection , value ,key ){
     for(var obj of collection) {
           if(obj[key[0]][key[1]][key[2]] == value)
           { 
               return obj
           }
     }
     return null;
}