我的数组看起来像这样
//loop through the array and fecth some rows based on some condition
function getHospitals(id,type){
var hospitals=[{"district_id":"1","type":"c","details":[{"name":"hello","address":"hello","number":"686678"}]},
{"district_id":"1","type":"g","details":[{"name":"hello","address":"hello","number":"686678"}}]}
]
//return array of results
return result;
}
现在我需要从数组中获取满足某些条件的行。 这是代码段
result
hospitals
数组包含select * from where district_id=id and type=type
数组中与条件匹配的行
喜欢
{{1}}
那么如何从上面的数组中选择一个符合上述条件的行呢?
答案 0 :(得分:0)
目前还不存在基于JavaScript数组的完整SQL解析器和存储系统。有一些被弃用的和实验性的东西像this sql parser一样只支持SELECT语句,但我强烈建议反对它。
相反,您可能需要查看lodash
(或underscore)。它们都有很多高级实用程序函数,这使得在数组和其他类型的集合上工作变得更加容易。
E.g。
select * from section_id = id和type = type
可以这样实现:
var matchingHospitals = _.where(hospitals, {district_id: id, type: type});
注意:_.where
返回一个数组。
另外,如果_.where
没有删除它,那么还有_.filter,_.find
等等......
答案 1 :(得分:0)
您可以使用Lodash来执行此操作。 https://lodash.com/docs#findWhere
来自lodash:
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false }
];
_.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user');
// → 'barney'
_.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user');
// → 'fred'
lodash中有很多搜索功能:find()findIndex(),...
答案 2 :(得分:0)
你可以使用jQuery' grep'功能如下:
function getHospitals(id, type){
var hospitals=[
{"district_id":"1","type":"c","details":[{"name":"hello","address":"hello","number":"686678"}]},
{"district_id":"1","type":"g","details":[{"name":"hello","address":"hello","number":"686678"}}]}
];
//return array of results
return $.grep(hospitals, function(e){
return (e.district_id == id && e.type == type);
});
}
希望这有帮助。
答案 3 :(得分:0)
//loop through the array and return all rows satisfying the conditions
function getHospitals(id,type){
var hospitals=[{
"district_id":"1","type":"c","details":[{"name":"hello","address":"hello","number":"686678"}]
},{"district_id":"1","type":"g","details":{"name":"hello","address":"hello","number":"686678"}}];
var matchingHospitals = []; //an array to save all the matching hospitals that satisfy the condition
for(var i in hospitals){ //loop through the data
var hospital = hospitals[i];
if(hospital.district_id==id && hospital.type==type){ //check condition
matchingHospitals.push(hospital); //push into matching array
}
}
//return array of results
return matchingHospitals; //return matching hospitals array
}
测试查询:
getHospitals("1","c")