使用类似查询的下划线过滤对象数组
Underscore filter array of object using like query
我有以下 Json.
{
"results": [
{
"id": "123",
"name": "Some Name"
},
{
"id": "124",
"name": "My Name"
},
{
"id": "125",
"name": "Johnson Johnson"
},
{
"id": "126",
"name": "Mike and Mike"
},
{
"id": "201",
"name": "abc xyz"
},
{
"id": "202",
"name": "abc befd"
},
{
"id": "210",
"name": "jki yuiu"
},
{
"id": "203",
"name": "asdfui uiuu"
},
{
"id": "204",
"name": "sfdhu uiu"
},
{
"id": "205",
"name": "asdfui uyu"
}
]
}
使用 Underscore 我想使用 sql 过滤上述数据,比如对 id 的查询。
例如,如果传递“2”,则应过滤 json 并 return 包含以 2 开头的 id 的新 json,如果我传递 20,则应 return 新 json id 以 20
开头
类似于sql like 查询然后return n 结果匹配,
更正:我想要以 id 2 开头的数据或我传递的任何参数我需要以它开头的数据
Array.prototype.filter
和 Array.prototype.slice
呢? (下划线也有类似的功能,但用普通JS就可以解决,为什么还要用)
function sqlLikeFilter(data, id, maxn) {
return data.result.filter(function(x) { return x.id == id; }).slice(0, maxn);
}
console.log(sqlLikeFilter(yourData, 125, 1));
试试这个
function(id){
var result = _.filter(results, function(value) {
return value.id === id
})
return result;
}
试试这个
function getResult(keyToFilter, valueStartsWith){
return _.filter(results, function(d){ return d[keyToFilter].startsWith(valueStartsWith); })
}
getResult("name", "asdfui");
[{
"id": "203",
"name": "asdfui uiuu"
},
{
"id": "205",
"name": "asdfui uyu"
}]
我有以下 Json.
{
"results": [
{
"id": "123",
"name": "Some Name"
},
{
"id": "124",
"name": "My Name"
},
{
"id": "125",
"name": "Johnson Johnson"
},
{
"id": "126",
"name": "Mike and Mike"
},
{
"id": "201",
"name": "abc xyz"
},
{
"id": "202",
"name": "abc befd"
},
{
"id": "210",
"name": "jki yuiu"
},
{
"id": "203",
"name": "asdfui uiuu"
},
{
"id": "204",
"name": "sfdhu uiu"
},
{
"id": "205",
"name": "asdfui uyu"
}
]
}
使用 Underscore 我想使用 sql 过滤上述数据,比如对 id 的查询。 例如,如果传递“2”,则应过滤 json 并 return 包含以 2 开头的 id 的新 json,如果我传递 20,则应 return 新 json id 以 20
开头类似于sql like 查询然后return n 结果匹配,
更正:我想要以 id 2 开头的数据或我传递的任何参数我需要以它开头的数据
Array.prototype.filter
和 Array.prototype.slice
呢? (下划线也有类似的功能,但用普通JS就可以解决,为什么还要用)
function sqlLikeFilter(data, id, maxn) {
return data.result.filter(function(x) { return x.id == id; }).slice(0, maxn);
}
console.log(sqlLikeFilter(yourData, 125, 1));
试试这个
function(id){
var result = _.filter(results, function(value) {
return value.id === id
})
return result;
}
试试这个
function getResult(keyToFilter, valueStartsWith){
return _.filter(results, function(d){ return d[keyToFilter].startsWith(valueStartsWith); })
}
getResult("name", "asdfui");
[{
"id": "203",
"name": "asdfui uiuu"
},
{
"id": "205",
"name": "asdfui uyu"
}]